router.GET("/hello",calcTime,func(c *gin.Context){}) 支持多个函数,每个函数一次调用。这样就可以拦截请求
c.Next() 可以在当前函数不退出的情况下,继续执行下一个中间件,等后续的处理完了,又回到当前中间件
go
package main
import "github.com/gin-gonic/gin"
import "fmt"
import "time"
func middleWare(c *gin.Context){
fmt.Println("将要访问index.html")
}
func calcTime(c *gin.Context){
time1 := time.Now().UnixNano()
// 调用后续得代码,
c.Next()
newTime := time.Now().UnixNano()
fmt.Printf("%v 纳秒",newTime - time1)
}
func main(){
router := gin.Default()
router.GET("/", middleWare, func(c *gin.Context){
c.String(200, "Hello world")
})
router.GET("/hello",calcTime,func(c *gin.Context){
c.String(200, "Hello world")
})
router.Run()
}
并发测试
wrk -t2 -c20 -d30s https://localhost:8000/hello
-t2并发2个线程-c2020个并发-d30s持续时间30秒
go
package main
import "github.com/gin-gonic/gin"
import "fmt"
import "time"
func middleWare(c *gin.Context){
fmt.Println("将要访问index.html")
}
func calcTime(c *gin.Context){
time1 := time.Now().UnixNano()
// 调用后续得代码,
c.Next()
newTime := time.Now().UnixNano()
_ = newTime - time1
}
func main(){
// 关闭所有日志
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(gin.Recovery())
router.GET("/", middleWare, func(c *gin.Context){
c.String(200, "Hello world")
})
router.GET("/hello",calcTime,func(c *gin.Context){
c.String(200, "Hello world")
})
router.Run()
}
bash
go run main.go &
wrk -t2 -c20 -d30s http://192.168.139.204:8080/hello
Running 30s test @ http://192.168.139.204:8080/hello
2 threads and 20 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 30.37ms 66.17ms 457.06ms 85.66%
Req/Sec 99.33k 41.62k 181.85k 71.14%
5472968 requests in 30.09s, 668.09MB read
Requests/sec: 181858.35
Transfer/sec: 22.20MB