router.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package routers
  2. import (
  3. "mtp2_if/controllers/cptrade"
  4. "mtp2_if/logger"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. // Swagger生成的文档
  8. _ "mtp2_if/docs"
  9. ginSwagger "github.com/swaggo/gin-swagger"
  10. "github.com/swaggo/gin-swagger/swaggerFiles"
  11. )
  12. // InitRouter 初始化路由器的方法
  13. func InitRouter() *gin.Engine {
  14. r := gin.New()
  15. // 设置日志中间件
  16. r.Use(ginLoggerMiddleware())
  17. // 设置奔溃中间件
  18. r.Use(ginRecoveryMiddleware())
  19. // Swagger
  20. r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
  21. // 路由分组
  22. apiR := r.Group("/api")
  23. // ************************ 产能预售 ************************
  24. cpTradeR := apiR.Group("CPTrade")
  25. // cpTradeR.Use(token.Auth())
  26. cpTradeR.Use()
  27. {
  28. // 查询产能预售申请表
  29. cpTradeR.GET("/QueryPreasleApply", cptrade.QueryPreasleApply)
  30. }
  31. return r
  32. }
  33. func ginLoggerMiddleware() gin.HandlerFunc {
  34. return func(c *gin.Context) {
  35. start := time.Now()
  36. c.Next()
  37. end := time.Now()
  38. latency := end.Sub(start)
  39. path := c.Request.URL.RequestURI()
  40. clientip := c.ClientIP()
  41. method := c.Request.Method
  42. statuscode := c.Writer.Status()
  43. logger.GetLogger().Infof("|%3d|%13v|%15s|%s %s",
  44. statuscode,
  45. latency,
  46. clientip,
  47. method,
  48. path)
  49. }
  50. }
  51. func ginRecoveryMiddleware() gin.HandlerFunc {
  52. return gin.RecoveryWithWriter(logger.GetLogWriter())
  53. }