定义程序计时中间件,然后定义2个路由,执行函数后应该打印统计时间,如下:

image.png
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
// 定义中间件
func myTime(c *gin.Context){
start := time.Now()
c.Next()
// 统计时间
since := time.Since(start)
fmt.Println("程序用时:",since)
}
func main() {
// 1. 创建路由器
r := gin.Default()
// 1.注册中间件
r.Use(myTime)
// {}为了代码规范
shoppingGroup:=r.Group("/shopping")
{
shoppingGroup.GET("/index",shopIndexHandler)
shoppingGroup.GET("/home",shopHomeHandler)
}
// 3.监听端口,默认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

结果.png
之前以为起两个默认路由,结果会报错的,而答案是起个路由组,使用两个GET请求。