core.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. package mux
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.bvbej.com/bvbej/base-golang/pkg/validator"
  6. "github.com/gin-gonic/gin/binding"
  7. "golang.org/x/time/rate"
  8. "net/http"
  9. "net/url"
  10. "runtime/debug"
  11. "time"
  12. "git.bvbej.com/bvbej/base-golang/pkg/color"
  13. "git.bvbej.com/bvbej/base-golang/pkg/env"
  14. "git.bvbej.com/bvbej/base-golang/pkg/errno"
  15. "git.bvbej.com/bvbej/base-golang/pkg/trace"
  16. "github.com/gin-contrib/pprof"
  17. "github.com/gin-gonic/gin"
  18. "github.com/prometheus/client_golang/prometheus/promhttp"
  19. cors "github.com/rs/cors/wrapper/gin"
  20. "go.uber.org/multierr"
  21. "go.uber.org/zap"
  22. )
  23. const (
  24. _EverySize = 1e3
  25. _MaxBurstSize = _EverySize * 60
  26. )
  27. var limiter = rate.NewLimiter(rate.Limit(_EverySize), _MaxBurstSize)
  28. type Option func(*option)
  29. type option struct {
  30. enableCors bool
  31. enableRate bool
  32. enablePProf bool
  33. enablePrometheus bool
  34. enableOpenBrowser string
  35. staticDirs []string
  36. panicNotify OnPanicNotify
  37. recordMetrics RecordMetrics
  38. }
  39. type Failure struct {
  40. ResultCode int `json:"result_code"` // 业务码
  41. ResultInfo string `json:"result_info"` // 描述信息
  42. }
  43. type Success struct {
  44. ResultCode int `json:"result_code"` // 业务码
  45. ResultData any `json:"result_data"` //返回数据
  46. }
  47. /******************************************************************************/
  48. // OnPanicNotify 发生panic时通知用
  49. type OnPanicNotify func(ctx Context, err any, stackInfo string)
  50. // RecordMetrics 记录prometheus指标用
  51. // 如果使用AliasForRecordMetrics配置了别名,uri将被替换为别名。
  52. type RecordMetrics func(method, uri string, success bool, costSeconds float64)
  53. // DisableTrace 禁用追踪链
  54. func DisableTrace(ctx Context) {
  55. ctx.disableTrace()
  56. }
  57. // WithPanicNotify 设置panic时的通知回调
  58. func WithPanicNotify(notify OnPanicNotify) Option {
  59. return func(opt *option) {
  60. opt.panicNotify = notify
  61. fmt.Println(color.Green("* [register panic notify]"))
  62. }
  63. }
  64. // WithRecordMetrics 设置记录prometheus记录指标回调
  65. func WithRecordMetrics(record RecordMetrics) Option {
  66. return func(opt *option) {
  67. opt.recordMetrics = record
  68. }
  69. }
  70. // WithEnableCors 开启CORS
  71. func WithEnableCors() Option {
  72. return func(opt *option) {
  73. opt.enableCors = true
  74. fmt.Println(color.Green("* [register cors]"))
  75. }
  76. }
  77. // WithEnableRate 开启限流
  78. func WithEnableRate() Option {
  79. return func(opt *option) {
  80. opt.enableRate = true
  81. fmt.Println(color.Green("* [register rate]"))
  82. }
  83. }
  84. // WithStaticDir 设置静态文件目录
  85. func WithStaticDir(dirs []string) Option {
  86. return func(opt *option) {
  87. opt.staticDirs = dirs
  88. fmt.Println(color.Green("* [register rate]"))
  89. }
  90. }
  91. // AliasForRecordMetrics 对请求uri起个别名,用于prometheus记录指标。
  92. // 如:Get /user/:username 这样的uri,因为username会有非常多的情况,这样记录prometheus指标会非常的不有好。
  93. func AliasForRecordMetrics(path string) HandlerFunc {
  94. return func(ctx Context) {
  95. ctx.setAlias(path)
  96. }
  97. }
  98. /******************************************************************************/
  99. // RouterGroup 包装gin的RouterGroup
  100. type RouterGroup interface {
  101. Group(string, ...HandlerFunc) RouterGroup
  102. IRoutes
  103. }
  104. var _ IRoutes = (*router)(nil)
  105. // IRoutes 包装gin的IRoutes
  106. type IRoutes interface {
  107. Any(string, ...HandlerFunc)
  108. GET(string, ...HandlerFunc)
  109. POST(string, ...HandlerFunc)
  110. DELETE(string, ...HandlerFunc)
  111. PATCH(string, ...HandlerFunc)
  112. PUT(string, ...HandlerFunc)
  113. OPTIONS(string, ...HandlerFunc)
  114. HEAD(string, ...HandlerFunc)
  115. }
  116. type router struct {
  117. group *gin.RouterGroup
  118. }
  119. func (r *router) Group(relativePath string, handlers ...HandlerFunc) RouterGroup {
  120. group := r.group.Group(relativePath, wrapHandlers(handlers...)...)
  121. return &router{group: group}
  122. }
  123. func (r *router) Any(relativePath string, handlers ...HandlerFunc) {
  124. r.group.Any(relativePath, wrapHandlers(handlers...)...)
  125. }
  126. func (r *router) GET(relativePath string, handlers ...HandlerFunc) {
  127. r.group.GET(relativePath, wrapHandlers(handlers...)...)
  128. }
  129. func (r *router) POST(relativePath string, handlers ...HandlerFunc) {
  130. r.group.POST(relativePath, wrapHandlers(handlers...)...)
  131. }
  132. func (r *router) DELETE(relativePath string, handlers ...HandlerFunc) {
  133. r.group.DELETE(relativePath, wrapHandlers(handlers...)...)
  134. }
  135. func (r *router) PATCH(relativePath string, handlers ...HandlerFunc) {
  136. r.group.PATCH(relativePath, wrapHandlers(handlers...)...)
  137. }
  138. func (r *router) PUT(relativePath string, handlers ...HandlerFunc) {
  139. r.group.PUT(relativePath, wrapHandlers(handlers...)...)
  140. }
  141. func (r *router) OPTIONS(relativePath string, handlers ...HandlerFunc) {
  142. r.group.OPTIONS(relativePath, wrapHandlers(handlers...)...)
  143. }
  144. func (r *router) HEAD(relativePath string, handlers ...HandlerFunc) {
  145. r.group.HEAD(relativePath, wrapHandlers(handlers...)...)
  146. }
  147. func wrapHandlers(handlers ...HandlerFunc) []gin.HandlerFunc {
  148. list := make([]gin.HandlerFunc, len(handlers))
  149. for i, handler := range handlers {
  150. fn := handler
  151. list[i] = func(c *gin.Context) {
  152. ctx := newContext(c)
  153. defer releaseContext(ctx)
  154. fn(ctx)
  155. }
  156. }
  157. return list
  158. }
  159. /******************************************************************************/
  160. var _ Mux = (*mux)(nil)
  161. type Mux interface {
  162. http.Handler
  163. Group(relativePath string, handlers ...HandlerFunc) RouterGroup
  164. Routes() gin.RoutesInfo
  165. HandlerFunc(relativePath string, handlerFunc gin.HandlerFunc)
  166. }
  167. type mux struct {
  168. engine *gin.Engine
  169. }
  170. func (m *mux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  171. m.engine.ServeHTTP(w, req)
  172. }
  173. func (m *mux) Group(relativePath string, handlers ...HandlerFunc) RouterGroup {
  174. return &router{
  175. group: m.engine.Group(relativePath, wrapHandlers(handlers...)...),
  176. }
  177. }
  178. func (m *mux) Routes() gin.RoutesInfo {
  179. return m.engine.Routes()
  180. }
  181. func (m *mux) HandlerFunc(relativePath string, handlerFunc gin.HandlerFunc) {
  182. m.engine.GET(relativePath, handlerFunc)
  183. }
  184. func New(logger *zap.Logger, options ...Option) (Mux, error) {
  185. if logger == nil {
  186. return nil, errors.New("logger required")
  187. }
  188. gin.SetMode(gin.ReleaseMode)
  189. binding.Validator = validator.Validator
  190. newMux := &mux{
  191. engine: gin.New(),
  192. }
  193. fmt.Println(color.Green(fmt.Sprintf("* [register env %s]", env.Active().Value())))
  194. // withoutLogPaths 这些请求,默认不记录日志
  195. withoutTracePaths := map[string]bool{
  196. "/metrics": true,
  197. "/favicon.ico": true,
  198. "/system/health": true,
  199. }
  200. opt := new(option)
  201. for _, f := range options {
  202. f(opt)
  203. }
  204. if opt.enablePProf {
  205. pprof.Register(newMux.engine)
  206. fmt.Println(color.Green("* [register pprof]"))
  207. }
  208. if opt.enablePrometheus {
  209. newMux.engine.GET("/metrics", gin.WrapH(promhttp.Handler()))
  210. fmt.Println(color.Green("* [register prometheus]"))
  211. }
  212. if opt.enableCors {
  213. newMux.engine.Use(cors.AllowAll())
  214. }
  215. if opt.staticDirs != nil {
  216. for _, dir := range opt.staticDirs {
  217. newMux.engine.StaticFS(dir, gin.Dir(dir, false))
  218. }
  219. }
  220. // recover两次,防止处理时发生panic,尤其是在OnPanicNotify中。
  221. newMux.engine.Use(func(ctx *gin.Context) {
  222. defer func() {
  223. if err := recover(); err != nil {
  224. logger.Error("got panic", zap.String("panic", fmt.Sprintf("%+v", err)), zap.String("stack", string(debug.Stack())))
  225. }
  226. }()
  227. ctx.Next()
  228. })
  229. newMux.engine.Use(func(ctx *gin.Context) {
  230. ts := time.Now()
  231. newCtx := newContext(ctx)
  232. defer releaseContext(newCtx)
  233. newCtx.init()
  234. newCtx.setLogger(logger)
  235. if !withoutTracePaths[ctx.Request.URL.Path] {
  236. if traceId := newCtx.GetHeader(trace.Header); traceId != "" {
  237. newCtx.setTrace(trace.New(traceId))
  238. } else {
  239. newCtx.setTrace(trace.New(""))
  240. }
  241. }
  242. defer func() {
  243. if err := recover(); err != nil {
  244. stackInfo := string(debug.Stack())
  245. logger.Error("got panic", zap.String("panic", fmt.Sprintf("%+v", err)), zap.String("stack", stackInfo))
  246. newCtx.AbortWithError(errno.NewError(
  247. http.StatusInternalServerError,
  248. http.StatusInternalServerError,
  249. http.StatusText(http.StatusInternalServerError)),
  250. )
  251. if notify := opt.panicNotify; notify != nil {
  252. notify(newCtx, err, stackInfo)
  253. }
  254. }
  255. if ctx.Writer.Status() == http.StatusNotFound {
  256. return
  257. }
  258. var (
  259. response any
  260. businessCode int
  261. businessCodeMsg string
  262. abortErr error
  263. graphResponse any
  264. )
  265. if ctx.IsAborted() {
  266. for i := range ctx.Errors { // gin error
  267. multierr.AppendInto(&abortErr, ctx.Errors[i])
  268. }
  269. if err := newCtx.abortError(); err != nil { // customer err
  270. multierr.AppendInto(&abortErr, err.GetErr())
  271. response = err
  272. businessCode = err.GetBusinessCode()
  273. businessCodeMsg = err.GetMsg()
  274. if x := newCtx.Trace(); x != nil {
  275. newCtx.SetHeader(trace.Header, x.ID())
  276. }
  277. ctx.JSON(err.GetHttpCode(), &Failure{
  278. ResultCode: businessCode,
  279. ResultInfo: businessCodeMsg,
  280. })
  281. }
  282. } else {
  283. response = newCtx.getPayload()
  284. if response != nil {
  285. if x := newCtx.Trace(); x != nil {
  286. newCtx.SetHeader(trace.Header, x.ID())
  287. }
  288. ctx.JSON(http.StatusOK, response)
  289. }
  290. }
  291. graphResponse = newCtx.getGraphPayload()
  292. if opt.recordMetrics != nil {
  293. uri := newCtx.Path()
  294. if alias := newCtx.Alias(); alias != "" {
  295. uri = alias
  296. }
  297. opt.recordMetrics(
  298. newCtx.Method(),
  299. uri,
  300. !ctx.IsAborted() && ctx.Writer.Status() == http.StatusOK,
  301. time.Since(ts).Seconds(),
  302. )
  303. }
  304. var t *trace.Trace
  305. if x := newCtx.Trace(); x != nil {
  306. t = x.(*trace.Trace)
  307. } else {
  308. return
  309. }
  310. decodedURL, _ := url.QueryUnescape(ctx.Request.URL.RequestURI())
  311. t.WithRequest(&trace.Request{
  312. TTL: "un-limit",
  313. Method: ctx.Request.Method,
  314. DecodedURL: decodedURL,
  315. Header: ctx.Request.Header,
  316. Body: string(newCtx.RawData()),
  317. })
  318. var responseBody any
  319. if response != nil {
  320. responseBody = response
  321. }
  322. if graphResponse != nil {
  323. responseBody = graphResponse
  324. }
  325. t.WithResponse(&trace.Response{
  326. Header: ctx.Writer.Header(),
  327. HttpCode: ctx.Writer.Status(),
  328. HttpCodeMsg: http.StatusText(ctx.Writer.Status()),
  329. BusinessCode: businessCode,
  330. BusinessCodeMsg: businessCodeMsg,
  331. Body: responseBody,
  332. CostSeconds: time.Since(ts).Seconds(),
  333. })
  334. t.Success = !ctx.IsAborted() && ctx.Writer.Status() == http.StatusOK
  335. t.CostSeconds = time.Since(ts).Seconds()
  336. logger.Info("core-interceptor",
  337. zap.Any("method", ctx.Request.Method),
  338. zap.Any("path", decodedURL),
  339. zap.Any("http_code", ctx.Writer.Status()),
  340. zap.Any("business_code", businessCode),
  341. zap.Any("success", t.Success),
  342. zap.Any("cost_seconds", t.CostSeconds),
  343. zap.Any("trace_id", t.Identifier),
  344. zap.Any("trace_info", t),
  345. zap.Error(abortErr),
  346. )
  347. }()
  348. ctx.Next()
  349. })
  350. if opt.enableRate {
  351. newMux.engine.Use(func(ctx *gin.Context) {
  352. newCtx := newContext(ctx)
  353. defer releaseContext(newCtx)
  354. if !limiter.Allow() {
  355. newCtx.AbortWithError(errno.NewError(
  356. http.StatusTooManyRequests,
  357. http.StatusTooManyRequests,
  358. http.StatusText(http.StatusTooManyRequests)),
  359. )
  360. return
  361. }
  362. ctx.Next()
  363. })
  364. }
  365. newMux.engine.NoMethod(wrapHandlers(DisableTrace)...)
  366. newMux.engine.NoRoute(wrapHandlers(DisableTrace)...)
  367. system := newMux.Group("/system")
  368. {
  369. // 健康检查
  370. system.GET("/health", func(ctx Context) {
  371. resp := &struct {
  372. Timestamp time.Time `json:"timestamp"`
  373. Environment string `json:"environment"`
  374. Host string `json:"host"`
  375. Status string `json:"status"`
  376. }{
  377. Timestamp: time.Now(),
  378. Environment: env.Active().Value(),
  379. Host: ctx.Host(),
  380. Status: "ok",
  381. }
  382. ctx.Payload(resp)
  383. })
  384. }
  385. return newMux, nil
  386. }