定義程序計(jì)時(shí)中間件,然后定義2個(gè)路由,執(zhí)行函數(shù)后應(yīng)該打印統(tǒng)計(jì)時(shí)間,如下:

image.png
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
// 定義中間件
func myTime(c *gin.Context){
start := time.Now()
c.Next()
// 統(tǒng)計(jì)時(shí)間
since := time.Since(start)
fmt.Println("程序用時(shí):",since)
}
func main() {
// 1. 創(chuàng)建路由器
r := gin.Default()
// 1.注冊中間件
r.Use(myTime)
// {}為了代碼規(guī)范
shoppingGroup:=r.Group("/shopping")
{
shoppingGroup.GET("/index",shopIndexHandler)
shoppingGroup.GET("/home",shopHomeHandler)
}
// 3.監(jiān)聽端口,默認(rèn)8080
r.Run(":8000")
}
func shopIndexHandler(c *gin.Context){
time.Sleep(5*time.Second)
}
func shopHomeHandler(c *gin.Context){
time.Sleep(5*time.Second)
}
localhost:8000/shopping/index
localhost:8000/shopping/home

結(jié)果.png
之前以為起兩個(gè)默認(rèn)路由,結(jié)果會(huì)報(bào)錯(cuò)的,而答案是起個(gè)路由組,使用兩個(gè)GET請求。