go-gin (youtebu自学) - 第三课 -- 自定义logger中间件

自定义logger中间件

  • 新建文件夹middleware
  • 新建文件middleware/logger.go
    package middleware
    
    import (
    	"fmt"
    	"time"
    
    	"github.com/gin-gonic/gin"
    )
    
    func Logger() gin.HandlerFunc {
    	return gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string {
    		return fmt.Sprintf(
    			"%s - [%s] %s %s %d %s\n",
    			params.ClientIP,
    			params.TimeStamp.Format(time.RFC822),
    			params.Method,
    			params.Path,
    			params.StatusCode,
    			params.Latency,
    		)
    	})
    }
    
  • server.go
    package main
    
    import (
    	"learn-gin/controller"
    	"learn-gin/middleware"
    	"learn-gin/service"
    	"net/http"
    
    	"github.com/gin-gonic/gin"
    )
    
    var (
    	blogService    service.BlogService       = service.New()
    	blogController controller.BlogController = controller.New(blogService)
    )
    
    func main() {
    	server := gin.New()
    
    	server.Use(gin.Recovery(), middleware.Logger()) // +
    
    	server.GET("blogs", func(c *gin.Context) {
    		c.JSON(http.StatusOK, blogController.FindAll())
    	})
    
    	server.POST("blogs", func(c *gin.Context) {
    		c.JSON(http.StatusCreated, blogController.Save(c))
    	})
    
    	server.Run(":8080")
    }
    
  • 运行
    go run server.go
    
  • 测试
    GET - localhost:8080/blogs // ::1 - [09 Aug 21 11:08 CST] GET /blogs 200 0s
    PSOT - localhost:8080/blogs // ::1 - [09 Aug 21 11:08 CST] POST /blogs 201 0s