service/library/middleware/timeout.go

29 lines
568 B
Go
Raw Normal View History

2024-05-15 19:09:45 +08:00
package middleware
import (
"net/http"
2024-05-16 20:43:21 +08:00
"service/api/base"
"service/api/consts"
2024-05-15 19:09:45 +08:00
"time"
"github.com/gin-contrib/timeout"
"github.com/gin-gonic/gin"
)
2024-05-16 20:43:21 +08:00
func timeoutHandler(ctx *gin.Context) {
ctx.AbortWithStatusJSON(http.StatusGatewayTimeout, base.BaseResponse{
Ret: consts.RetCodeFail,
Msg: "出了个小问题,请稍后再试~",
2024-05-15 19:09:45 +08:00
})
}
func TimeoutMiddleware() gin.HandlerFunc {
return timeout.New(
2024-05-16 20:43:21 +08:00
timeout.WithTimeout(3000*time.Millisecond),
2024-05-15 19:09:45 +08:00
timeout.WithHandler(func(c *gin.Context) {
c.Next()
}),
2024-05-16 20:43:21 +08:00
timeout.WithResponse(timeoutHandler),
2024-05-15 19:09:45 +08:00
)
}