使用 Go 处理中间件

简介

开发 web 应用的时候, 不少地方都须要使用中间件来统一处理一些任务,
好比记录日志, 登陆校验等.git

gin 也提供了中间件功能.github

gin 的中间件

在项目建立之初, 就已经导入了一些中间件, 当时没有仔细介绍.web

g.Use(gin.Logger())
g.Use(gin.Recovery())
g.Use(middleware.NoCache())
g.Use(middleware.Options())
g.Use(middleware.Secure())

前面两个是 gin 自带的中间件, 分别是日志记录和错误恢复.
后面三个是设置一些 header, 具体是阻止缓存响应, 响应 options 请求,
以及浏览器安全设置.json

// 阻止缓存响应
func NoCache() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        ctx.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
        ctx.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
        ctx.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
        ctx.Next()
    }
}

// 响应 options 请求, 并退出
func Options() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        if ctx.Request.Method != "OPTIONS" {
            ctx.Next()
        } else {
            ctx.Header("Access-Control-Allow-Origin", "*")
            ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
            ctx.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
            ctx.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
            ctx.Header("Content-Type", "application/json")
            ctx.AbortWithStatus(200)
        }
    }
}

// 安全设置
func Secure() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        ctx.Header("Access-Control-Allow-Origin", "*")
        ctx.Header("X-Frame-Options", "DENY")
        ctx.Header("X-Content-Type-Options", "nosniff")
        ctx.Header("X-XSS-Protection", "1; mode=block")
        if ctx.Request.TLS != nil {
            ctx.Header("Strict-Transport-Security", "max-age=31536000")
        }

        // Also consider adding Content-Security-Policy headers
        // ctx.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
    }
}

gin 的中间件结构就是一个返回 func(ctx *gin.Context) 的函数,
又叫作 gin.HandlerFunc. 本质上和普通的 handler 没什么不一样,
gin.HandlerFuncfunc(*Context) 的别名.浏览器

中间件能够被定义在三个地方缓存

  • 全局中间件
  • Group 中间件
  • 单个路由中间件

一点须要注意的是在 middleware 和 handler 中使用 goroutine 时,
应该使用 gin.Context 的只读副本, 例如 cCp := context.Copy().安全

另外一点则是注意中间件的顺序.app

官方的示例以下:框架

func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()

        // Set example variable
        c.Set("example", "12345")

        // before request

        c.Next()

        // after request
        latency := time.Since(t)
        log.Print(latency)

        // access the status we are sending
        status := c.Writer.Status()
        log.Println(status)
    }
}

建立中间件

介绍了 gin 的中间件知识以后, 就能够根据需求使用中间件了.ide

实现一个中间件在每一个请求中设置 X-Request-Id 头.

// 在请求头中设置 X-Request-Id
func RequestId() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        requestId := ctx.Request.Header.Get("X-Request-Id")

        if requestId == "" {
            requestId = uuid.NewV4().String()
        }

        ctx.Set("X-Request-Id", requestId)

        ctx.Header("X-Request-Id", requestId)
        ctx.Next()
    }
}

设置 header 的同时保存在 context 内部, 经过设置惟一的 ID 以后,
就能够追踪一系列的请求了.

再来实现一个日志记录的中间件, 虽然 gin 已经自带了日志记录的中间件,
但本身实现能够更加个性化.

// 定义日志组件, 记录每个请求
func Logging() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        path := ctx.Request.URL.Path
        method := ctx.Request.Method
        ip := ctx.ClientIP()

        // 只记录特定的路由
        reg := regexp.MustCompile("(/v1/user|/login)")
        if !reg.MatchString(path) {
            return
        }

        var bodyBytes []byte
        if ctx.Request.Body != nil {
            bodyBytes, _ = ioutil.ReadAll(ctx.Request.Body)
        }
        // 读取后写回
        ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

        blw := &bodyLogWriter{
            body:           bytes.NewBufferString(""),
            ResponseWriter: ctx.Writer,
        }
        ctx.Writer = blw

        start := time.Now()
        ctx.Next()
        // 计算延迟, 和 gin.Logger 的差距有点大
        // 这是由于 middleware 相似栈, 先进后出, ctx.Next() 是转折点
        // 因此 gin.Logger 放在最前, 记录总时长
        // Logging 放在最后, 记录实际运行的时间, 不包含其余中间件的耗时
        end := time.Now()
        latency := end.Sub(start)

        code, message := -1, ""
        var response handler.Response
        if err := json.Unmarshal(blw.body.Bytes(), &response); err != nil {
            logrus.Errorf(
                "response body 不能被解析为 model.Response struct, body: `%s`, err: `%v`",
                blw.body.Bytes(),
                err,
            )
            code = errno.InternalServerError.Code
            message = err.Error()
        } else {
            code = response.Code
            message = response.Message
        }

        logrus.WithFields(logrus.Fields{
            "latency": fmt.Sprintf("%s", latency),
            "ip":      ip,
            "method":  method,
            "path":    path,
            "code":    code,
            "message": message,
        }).Info("记录请求")
    }
}

在注册中间件的时候, 将 Logging 放在全局中间件的最后,
将 gin.Logger() 放在全局中间件的最开始.
经过对比延迟, 你能够发现, 在 handler 处理比较快时,
中间件在总请求耗时中占据了很大的比例.

因此, 中间件虽然很是实用, 但须要控制全局中间件的数量.

总结

中间件是很是实用的, 基本上 web 框架都会实现.

当前部分的代码

做为版本 v0.8.0

相关文章
相关标签/搜索