proxy.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package engine
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "go_server/base/config"
  6. "go_server/base/core"
  7. "go_server/global"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "strings"
  12. )
  13. // 重定向配置
  14. var pathRewrite = map[string]string{
  15. "/health/liveness": "/health/liveness",
  16. }
  17. // 系统重定向
  18. func proxyPathRewrite(rawPath string) string {
  19. // 根据路径选择代理地址
  20. originalPath := rawPath // 路径重写
  21. // 重定向
  22. for pattern, replacement := range pathRewrite {
  23. if pattern == originalPath {
  24. rawPath = replacement
  25. break
  26. }
  27. }
  28. return strings.ReplaceAll(rawPath, "/admin/api/proxy", "/api")
  29. //return "/api" + strings.TrimPrefix(rawPath, "/admin/api/proxy")
  30. }
  31. // todo 通过请求路径解析出代理URL
  32. // biz 配置代理请求地址
  33. // /admin/api/proxy 默认请求地址前缀
  34. // biz 配置 proxy-alias 根据代理别名获取配置的URL
  35. // 如业务服务路径未保持一致 则使用默认代理地址
  36. func getTargetByPath(rewPath string) string {
  37. aliasSplit := strings.Split(strings.TrimPrefix(rewPath, "/admin/api/proxy"), "/")
  38. for _, alias := range aliasSplit {
  39. if alias != "" {
  40. return proxyAddrByAlias(alias)
  41. }
  42. }
  43. // 未找到则使用默认代理地址
  44. return config.AppConf().ProxyUrl
  45. }
  46. func proxyAddrByAlias(dbAlias string) string {
  47. // dbname转换为alias
  48. for k, dbName := range global.AMS_BIZ_ALIAS_DB_MAP {
  49. if dbName == dbAlias {
  50. dbAlias = k
  51. }
  52. }
  53. v, ok := global.AMS_BIZ_ALIAS_PROXY_MAP[dbAlias]
  54. if !ok {
  55. // 兼容直接通过数据库找到对应的连接
  56. return config.AppConf().ProxyUrl
  57. }
  58. return v
  59. }
  60. // 使用中间件代理转发 target string, pathRewrite map[string]string
  61. func createReverseProxy() gin.HandlerFunc {
  62. return func(c *gin.Context) {
  63. reqPath := c.Request.URL.Path
  64. core.Log.Infof("管理后台请求路径:%s", reqPath)
  65. target := getTargetByPath(reqPath)
  66. core.Log.Infof("代理URL:%s", target)
  67. remote, err := url.Parse(target)
  68. if err != nil {
  69. panic(err)
  70. }
  71. // 解析path 选择目标服务
  72. authID := c.GetInt64("userId")
  73. proxy := httputil.NewSingleHostReverseProxy(remote)
  74. proxy.Director = func(req *http.Request) {
  75. req.Header = c.Request.Header
  76. req.Host = remote.Host
  77. req.URL.Scheme = remote.Scheme
  78. req.URL.Host = remote.Host
  79. sign, _ := core.BuildSignMessage()
  80. req.Header.Set(core.SignKey, sign)
  81. core.Log.Infof("sign:%s", sign)
  82. req.Header.Set("authId", fmt.Sprintf("%d", authID))
  83. // 路径重定向
  84. req.URL.Path = proxyPathRewrite(req.URL.Path)
  85. core.Log.Infof("代理请求路径:%s%s", remote, req.URL.Path)
  86. }
  87. proxy.ServeHTTP(c.Writer, c.Request)
  88. }
  89. }