framework1/framework/middleware/timeout.go

44 lines
928 B
Go
Raw Normal View History

2024-10-18 14:41:55 +08:00
package middleware
import (
"context"
"fmt"
2024-10-18 17:21:19 +08:00
"github.com/Superdanda/hade/framework/gin"
2024-10-18 14:41:55 +08:00
"log"
"net/http"
"time"
)
2024-10-18 17:21:19 +08:00
func Timeout(d time.Duration) gin.HandlerFunc {
2024-10-18 14:41:55 +08:00
// 使用函数回调
2024-10-18 17:21:19 +08:00
return func(c *gin.Context) {
2024-10-18 14:41:55 +08:00
finish := make(chan struct{}, 1)
panicChan := make(chan interface{}, 1)
// 执行业务逻辑前预操作初始化超时context
durationCtx, cancel := context.WithTimeout(c.BaseContext(), d)
defer cancel()
go func() {
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
// 使用next执行具体的业务逻辑
c.Next()
finish <- struct{}{}
}()
// 执行业务逻辑后操作
select {
case p := <-panicChan:
2024-10-18 17:21:19 +08:00
c.ISetStatus(http.StatusInternalServerError).IJson("time out")
2024-10-18 14:41:55 +08:00
log.Println(p)
case <-finish:
fmt.Println("finish")
case <-durationCtx.Done():
2024-10-18 17:21:19 +08:00
c.ISetStatus(http.StatusInternalServerError).IJson("time out")
2024-10-18 14:41:55 +08:00
}
}
}