1
0

server.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package micro
  2. import (
  3. "context"
  4. "dashoo.cn/micro_libary/myerrors"
  5. "github.com/gogf/gf/v2/encoding/gbase64"
  6. "github.com/gogf/gf/v2/encoding/gjson"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/os/gctx"
  9. "github.com/rcrowley/go-metrics"
  10. "github.com/rpcxio/rpcx-consul/serverplugin"
  11. "github.com/smallnest/rpcx/server"
  12. "github.com/smallnest/rpcx/share"
  13. "time"
  14. )
  15. const Tenant = "Tenant"
  16. func CreateAndInitService(basePath string) *server.Server {
  17. var ctx = gctx.New()
  18. bindAddr, _ := g.Config().Get(ctx, "setting.bind-addr")
  19. registryType, _ := g.Config().Get(ctx, "setting.registry-type")
  20. registryAddr, _ := g.Config().Get(ctx, "setting.registry-addr")
  21. s := server.NewServer()
  22. g.Log().Infof(context.Background(), "服务启动, BindName: %v, BindAddr: %s", basePath, bindAddr.String())
  23. if registryType.String() == "consul" {
  24. addConsulRegistryPlugin(ctx, s, basePath, bindAddr.String(), registryAddr.String())
  25. }
  26. return s
  27. }
  28. func addConsulRegistryPlugin(ctx context.Context, s *server.Server, basePath, srvAddr, consulAddr string) {
  29. r := &serverplugin.ConsulRegisterPlugin{
  30. ServiceAddress: "tcp@" + srvAddr,
  31. ConsulServers: []string{consulAddr},
  32. BasePath: basePath,
  33. Metrics: metrics.NewRegistry(),
  34. UpdateInterval: time.Minute,
  35. }
  36. err := r.Start()
  37. if err != nil {
  38. g.Log().Fatal(ctx, err)
  39. }
  40. g.Log().Infof(ctx, "注册到Consul: %v, basePath: %v, MicorSrv: %v", consulAddr, basePath, srvAddr)
  41. s.Plugins.Add(r)
  42. }
  43. //// HandleAuth 处理身份验证
  44. //func HandleAuth(ctx context.Context, req *protocol.Message, token string, authExcludePaths []string) error {
  45. // tenant := getTenant(req)
  46. // g.Log().Infof(ctx, " ServicePath: %s, ServiceMethod: %s,Tenant:%s", req.ServicePath, req.ServiceMethod, tenant)
  47. //
  48. // reqPath := "/" + req.ServicePath + "/" + req.ServiceMethod
  49. // if authPath(reqPath, authExcludePaths) {
  50. // req.Metadata["authExclude"] = "false"
  51. // var rsp gtoken.Resp
  52. // notAuthSrv := ctx.Value("NotAuthSrv")
  53. // if notAuthSrv != nil && notAuthSrv.(bool) {
  54. // rsp = gtoken.GFToken.ValidToken(ctx, token)
  55. // } else {
  56. // ctx = context.WithValue(ctx, share.ReqMetaDataKey, map[string]string{"tenant": tenant})
  57. // rsp = validToken(ctx, token)
  58. // }
  59. //
  60. // if rsp.Code != 0 && rsp.Code != 200 {
  61. // return gerror.New("Token 认证失败!")
  62. // }
  63. // if req.Metadata != nil {
  64. // req.Metadata["userInfo"] = rsp.DataString()
  65. // }
  66. // return nil
  67. // }
  68. // return nil
  69. //}
  70. //
  71. //// 判断路径是否需要进行认证拦截
  72. //// return true 需要认证
  73. //func authPath(urlPath string, authExcludePaths []string) bool {
  74. // // 去除后斜杠
  75. // if strings.HasSuffix(urlPath, "/") {
  76. // urlPath = gstr.SubStr(urlPath, 0, len(urlPath)-1)
  77. // }
  78. //
  79. // // 排除路径处理,到这里nextFlag为true
  80. // for _, excludePath := range authExcludePaths {
  81. // tmpPath := excludePath
  82. // // 前缀匹配
  83. // if strings.HasSuffix(tmpPath, "/*") {
  84. // tmpPath = gstr.SubStr(tmpPath, 0, len(tmpPath)-2)
  85. // if gstr.HasPrefix(urlPath, tmpPath) {
  86. // // 前缀匹配不拦截
  87. // return false
  88. // }
  89. // } else {
  90. // // 全路径匹配
  91. // if strings.HasSuffix(tmpPath, "/") {
  92. // tmpPath = gstr.SubStr(tmpPath, 0, len(tmpPath)-1)
  93. // }
  94. // if urlPath == tmpPath {
  95. // // 全路径匹配不拦截
  96. // return false
  97. // }
  98. // }
  99. // }
  100. // return true
  101. //}
  102. //
  103. //// 验证token
  104. //func validToken(ctx context.Context, token string) gtoken.Resp {
  105. // grsp := gtoken.Resp{}
  106. // if token == "" {
  107. // grsp.Code = 401
  108. // grsp.Msg = "valid token empty"
  109. // return grsp
  110. // }
  111. //
  112. // authService := InitMicroSrvClient(ctx, "Auth", "micro_srv.auth")
  113. // defer authService.Close()
  114. // rsp := &gtoken.Resp{}
  115. // err := authService.Call(ctx, "ValidToken", token, rsp)
  116. // if err != nil {
  117. // g.Log().Error(ctx, err)
  118. // grsp.Code = 401
  119. // return grsp
  120. // }
  121. // grsp.Code = int(rsp.Code)
  122. // grsp.Msg = rsp.Msg
  123. // grsp.Data = rsp.Data
  124. // return grsp
  125. //}
  126. //
  127. //func getTenant(msg *protocol.Message) string {
  128. // var tenant string
  129. // if msg.Metadata != nil {
  130. // tenant = msg.Metadata[Tenant]
  131. // }
  132. // return tenant
  133. //}
  134. // GetTenant 从context中获取租户码
  135. func GetTenant(ctx context.Context) (string, error) {
  136. reqMeta := ctx.Value(share.ReqMetaDataKey).(map[string]string)
  137. tenant, ok := reqMeta["tenant"]
  138. if !ok {
  139. return "", myerrors.TipsError("不存在租户码")
  140. }
  141. return tenant, nil
  142. }
  143. // IsAuthExclude 是否进行auth验证
  144. func IsAuthExclude(ctx context.Context) bool {
  145. reqMeta := ctx.Value(share.ReqMetaDataKey).(map[string]string)
  146. flag, ok := reqMeta["authExclude"]
  147. if !ok || flag == "true" {
  148. return true
  149. }
  150. return false
  151. }
  152. // GetUserInfo 从context中获取UserInfo
  153. func GetUserInfo(ctx context.Context) (UserInfo, error) {
  154. reqMeta := ctx.Value(share.ReqMetaDataKey).(map[string]string)
  155. userStr, ok := reqMeta["userInfo"]
  156. if !ok {
  157. return UserInfo{}, myerrors.TipsError("用户信息获取失败,请重新登录。")
  158. }
  159. userInfo, err := getUserInfoDataString(ctx, userStr)
  160. if err != nil {
  161. return UserInfo{}, myerrors.TipsError("用户信息解码失败。")
  162. }
  163. return userInfo, nil
  164. }
  165. // getUserInfoDataString 从userInfo字符串转换成对象
  166. func getUserInfoDataString(ctx context.Context, userInfoString string) (UserInfo, error) {
  167. var userInfo UserInfo
  168. //uuid := ""
  169. if j, err := gjson.DecodeToJson(userInfoString); err != nil {
  170. g.Log().Error(ctx, err)
  171. return userInfo, err
  172. } else {
  173. j.SetViolenceCheck(true)
  174. err = j.Scan(&userInfo)
  175. if err != nil {
  176. g.Log().Error(ctx, err)
  177. return userInfo, err
  178. }
  179. }
  180. return userInfo, nil
  181. }
  182. // GetBrowserInfo 从context中获取ClientIP和UserAgent
  183. func GetBrowserInfo(ctx context.Context) (clientIP string, userAgent string, err error) {
  184. reqMeta := ctx.Value(share.ReqMetaDataKey).(map[string]string)
  185. clientIP, ok := reqMeta["clientIP"]
  186. if !ok {
  187. return "", "", myerrors.TipsError("BrowserInfo获取失败")
  188. }
  189. userAgent, ok = reqMeta["userAgent"]
  190. if !ok {
  191. return "", "", myerrors.TipsError("BrowserInfo获取失败")
  192. }
  193. userAgent, err = gbase64.DecodeToString(userAgent)
  194. return
  195. }