router.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package routers
  2. import (
  3. "mtp2_if/logger"
  4. "mtp2_if/token"
  5. "net/http"
  6. "time"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // InitRouter 初始化路由器的方法
  10. func InitRouter() *gin.Engine {
  11. r := gin.New()
  12. // 设置日志中间件
  13. r.Use(ginLoggerMiddleware())
  14. // 设置奔溃中间件
  15. r.Use(ginRecoveryMiddleware())
  16. // 路由分组
  17. apiR := r.Group("/api")
  18. apiR.Use(token.Auth())
  19. {
  20. // 测试
  21. apiR.GET("/ping", func(c *gin.Context) {
  22. c.JSON(http.StatusOK, gin.H{
  23. "code": 0,
  24. "msg": "pong",
  25. "data": nil,
  26. })
  27. })
  28. }
  29. return r
  30. }
  31. func ginLoggerMiddleware() gin.HandlerFunc {
  32. return func(c *gin.Context) {
  33. start := time.Now()
  34. c.Next()
  35. end := time.Now()
  36. latency := end.Sub(start)
  37. path := c.Request.URL.RequestURI()
  38. clientip := c.ClientIP()
  39. method := c.Request.Method
  40. statuscode := c.Writer.Status()
  41. logger.GetLogger().Infof("|%3d|%13v|%15s|%s %s",
  42. statuscode,
  43. latency,
  44. clientip,
  45. method,
  46. path)
  47. }
  48. }
  49. func ginRecoveryMiddleware() gin.HandlerFunc {
  50. return gin.RecoveryWithWriter(logger.GetLogWriter())
  51. }