manager.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package router
  2. import (
  3. "fmt"
  4. "gateway/common/db"
  5. . "gateway/common/gatecode"
  6. "github.com/gogf/gf/v2/net/ghttp"
  7. "github.com/gogf/gf/v2/util/gconv"
  8. )
  9. type Manager struct {
  10. routers map[string]Router
  11. }
  12. // InitRouterManager 初始化系统代理路由
  13. func InitRouterManager() (*Manager, error) {
  14. res := db.GateWatMySql.Query("SELECT status,middleground_code,url,function_code,ischeck,ischeck_auth,ischeck_blacklist,timeout,remark,deduct_source,ischeck_status FROM front_proxy")
  15. if res == nil || len(*res) == 0 {
  16. return nil, fmt.Errorf("未发现可用路由")
  17. }
  18. routerManager := &Manager{
  19. routers: make(map[string]Router),
  20. }
  21. for _, row := range *res {
  22. if url := gconv.String(row["url"]); url != "" {
  23. routerManager.routers[url] = Router{
  24. Status: gconv.Int(row["status"]),
  25. PowerCheck: gconv.Int(row["ischeck"]),
  26. AccountCheck: gconv.Int(row["ischeck_status"]),
  27. AuthCheck: gconv.Int(row["ischeck_auth"]),
  28. BlackCheck: gconv.Int(row["ischeck_blacklist"]) == 1,
  29. Deduct: gconv.Int(row["deduct_source"]),
  30. FuncCode: gconv.String(row["function_code"]),
  31. MiddleCode: gconv.String(row["middleground_code"]),
  32. ReqUrl: url,
  33. TimeOut: gconv.Int64(row["timeout"]),
  34. Remark: gconv.String(row["remark"]),
  35. }
  36. }
  37. }
  38. return routerManager, nil
  39. }
  40. // GetRouterRule 获取路由规则
  41. func (m *Manager) GetRouterRule(url string) (*Router, error) {
  42. // WillDo:后续需要增加正则匹配
  43. rule, exists := m.routers[url]
  44. if !exists {
  45. return nil, NewErrorWithCode(GATEWAY_ROUTER_NOTFIND, fmt.Sprintf("未找到请求地址%s,请检查是否注册到数据库\n", url))
  46. }
  47. if rule.Status != 1 {
  48. return nil, NewErrorWithCode(GATEWAY_ROUTER_UPHOLD, fmt.Sprintf("接口状态:%d\n", rule.Status))
  49. }
  50. return &rule, nil
  51. }
  52. // InfusionContext 注入通用结构体gContext
  53. func (m *Manager) InfusionContext(r *ghttp.Request) (err error) {
  54. var router *Router
  55. var GCtx = &GContext{}
  56. router, err = m.GetRouterRule(r.RequestURI)
  57. if err != nil {
  58. r.SetCtxVar(GContextKey, GCtx)
  59. return
  60. }
  61. GCtx.RouterRule = router
  62. //获取session
  63. jySess, _ := InitJySessionContext(r)
  64. GCtx.Sess = jySess
  65. r.SetCtxVar(GContextKey, GCtx)
  66. return
  67. }