The source code

Github.com/zsl10/gin-e…

The instance

  • Code:
package main

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin") // Define MiddleWare func MiddleWare() gin.HandlerFunc {return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("Middleware is starting to execute.")
		c.Set("request"."Middleware") // Execute the routing function c.next () status := c.whiter.status () fmt.println ()"Middleware execution completed", status)
		t2 := time.Since(t)
		fmt.Println("time:", t2)
	}
}

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

	}
	r.Run(": 8080")}Copy the code
  • Run:
Middleware begin to execute the request: 200 time: middleware middleware has been completed (including 91.315 s/GIN 2020/01/06-16:36:31 | | 200 | (including 101.12 s 127.0.0.1 | GET/md2Copy the code