gin实例--局部中间件(10)

902 阅读1分钟

源码

github.com/zsl10/gin-e…

实例

  • 代码
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// 定义中间件
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行了")
		// 设置变量到Context的key中,可以通过c.Get()获取
		c.Set("request", "中间件")
		status := c.Writer.Status()
		fmt.Println("中间件执行完毕", status)
		t2 := time.Since(t)
		fmt.Println("time:", t2)
	}
}

func main() {
	r := gin.Default()
	{
		r.GET("/md3",MiddleWare(),func(c *gin.Context) {
			req, _ := c.Get("request")
			fmt.Println("request:", req)
			c.JSON(200, gin.H{"request": req})
		})

		r.GET("/test",func(c *gin.Context) {
			c.String(http.StatusOK,"ok")
		})
	}
	r.Run(":8080")
}
  • 运行
[GIN-debug] Listening and serving HTTP on :8080
中间件开始执行了
中间件执行完毕 200
time: 49.758µs
request: 中间件
[GIN] 2020/01/06 - 16:48:12 | 200 |      175.31µs |       127.0.0.1 | GET      /md3
[GIN] 2020/01/06 - 16:48:20 | 404 |       1.659µs |       127.0.0.1 | GET      /md4
[GIN] 2020/01/06 - 16:48:30 | 200 |      38.703µs |       127.0.0.1 | GET      /test