manager.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 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. AuthCheck: gconv.Int(row["ischeck_auth"]),
  27. BlackCheck: gconv.Int(row["ischeck_blacklist"]) == 1,
  28. FuncCode: gconv.String(row["function_code"]),
  29. MiddleCode: gconv.String(row["middleground_code"]),
  30. ReqUrl: url,
  31. TimeOut: gconv.Int64(row["timeout"]),
  32. Remark: gconv.String(row["remark"]),
  33. }
  34. }
  35. }
  36. return routerManager, nil
  37. }
  38. // GetRouterRule 获取路由规则
  39. func (m *Manager) GetRouterRule(url string) (*Router, error) {
  40. // WillDo:后续需要增加正则匹配
  41. rule, exists := m.routers[url]
  42. if !exists {
  43. return nil, NewErrorWithCode(GATEWAY_ROUTER_NOTFIND, fmt.Sprintf("未找到请求地址%s,请检查是否注册到数据库\n", url))
  44. }
  45. if rule.Status != 1 {
  46. return nil, NewErrorWithCode(GATEWAY_ROUTER_UPHOLD, fmt.Sprintf("接口状态:%d\n", rule.Status))
  47. }
  48. return &rule, nil
  49. }
  50. // InfusionContext 注入通用结构体gContext
  51. func (m *Manager) InfusionContext(r *ghttp.Request) (err error) {
  52. var router *Router
  53. var GCtx = &GContext{}
  54. router, err = m.GetRouterRule(r.RequestURI)
  55. if err != nil {
  56. r.SetCtxVar(GContextKey, GCtx)
  57. return
  58. }
  59. GCtx.RouterRule = router
  60. //获取session
  61. jySess, _ := InitJySessionContext(r)
  62. GCtx.UserId = jySess.UserId
  63. GCtx.SessData = jySess.Data
  64. r.SetCtxVar(GContextKey, GCtx)
  65. return
  66. }