| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package routers
- import (
- "mtp2_if/logger"
- "mtp2_if/token"
- "net/http"
- "time"
- "github.com/gin-gonic/gin"
- )
- // InitRouter 初始化路由器的方法
- func InitRouter() *gin.Engine {
- r := gin.New()
- // 设置日志中间件
- r.Use(ginLoggerMiddleware())
- // 设置奔溃中间件
- r.Use(ginRecoveryMiddleware())
- // 路由分组
- apiR := r.Group("/api")
- apiR.Use(token.Auth())
- {
- // 测试
- apiR.GET("/ping", func(c *gin.Context) {
- c.JSON(http.StatusOK, gin.H{
- "code": 0,
- "msg": "pong",
- "data": nil,
- })
- })
- }
- return r
- }
- func ginLoggerMiddleware() gin.HandlerFunc {
- return func(c *gin.Context) {
- start := time.Now()
- c.Next()
- end := time.Now()
- latency := end.Sub(start)
- path := c.Request.URL.RequestURI()
- clientip := c.ClientIP()
- method := c.Request.Method
- statuscode := c.Writer.Status()
- logger.GetLogger().Infof("|%3d|%13v|%15s|%s %s",
- statuscode,
- latency,
- clientip,
- method,
- path)
- }
- }
- func ginRecoveryMiddleware() gin.HandlerFunc {
- return gin.RecoveryWithWriter(logger.GetLogWriter())
- }
|