This commit is contained in:
lwl0608 2024-05-16 20:43:21 +08:00
parent b57a826749
commit 0ec33fa81b
5 changed files with 28 additions and 8 deletions

View File

@ -60,6 +60,7 @@ func Init(r *gin.Engine) {
// healthcheck
r.GET("/healthcheck", Healthcheck)
r.GET("/timeout", Timeout)
// Hello World!
helloWorldGroup := r.Group("/hello_world", Prepare())

View File

@ -0,0 +1,16 @@
package controller
import (
"github.com/gin-gonic/gin"
"service/bizcommon/util"
"time"
)
func Timeout(ctx *gin.Context) {
time.Sleep(time.Second * 6)
data := map[string]interface{}{
"time": time.Now().Unix(),
"time_str": util.GetTodayZeroTime().Format(time.RFC3339),
}
ReplyOk(ctx, data)
}

View File

@ -12,6 +12,7 @@ func NewRouter() *gin.Engine {
router := gin.New()
router.Use(middleware.LoggerMiddleware(gin.LoggerConfig{}))
router.Use(gin.RecoveryWithWriter(logger.Global.Out))
router.Use(middleware.TimeoutMiddleware())
return router
}

View File

@ -94,8 +94,8 @@ func registerSD(ip string, port int) error {
}
func setServerStatusFD(status string) {
serverStatusFdPath := "/Users/erwin/SERVER_STATUS_FD"
cmd := exec.Command("echo", fmt.Sprintf("%s > %s", status, serverStatusFdPath))
serverStatusFdPath := "/app/SERVER_STATUS_FD"
cmd := exec.Command("sh", "-c", fmt.Sprintf("echo %s > %s", status, serverStatusFdPath))
err := cmd.Run()
if err != nil {
logger.Info("run cmd fail, p: %v, err: %v", serverStatusFdPath, err)

View File

@ -2,25 +2,27 @@ package middleware
import (
"net/http"
"service/api/base"
"service/api/consts"
"time"
"github.com/gin-contrib/timeout"
"github.com/gin-gonic/gin"
)
func testResponse(c *gin.Context) {
c.JSON(http.StatusGatewayTimeout, gin.H{
"code": http.StatusGatewayTimeout,
"msg": "timeout",
func timeoutHandler(ctx *gin.Context) {
ctx.AbortWithStatusJSON(http.StatusGatewayTimeout, base.BaseResponse{
Ret: consts.RetCodeFail,
Msg: "出了个小问题,请稍后再试~",
})
}
func TimeoutMiddleware() gin.HandlerFunc {
return timeout.New(
timeout.WithTimeout(5000*time.Millisecond),
timeout.WithTimeout(3000*time.Millisecond),
timeout.WithHandler(func(c *gin.Context) {
c.Next()
}),
timeout.WithResponse(testResponse),
timeout.WithResponse(timeoutHandler),
)
}