framework1/framework/middleware/timeout.go

44 lines
928 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"context"
"fmt"
"github.com/Superdanda/hade/framework/gin"
"log"
"net/http"
"time"
)
func Timeout(d time.Duration) gin.HandlerFunc {
// 使用函数回调
return func(c *gin.Context) {
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:
c.ISetStatus(http.StatusInternalServerError).IJson("time out")
log.Println(p)
case <-finish:
fmt.Println("finish")
case <-durationCtx.Done():
c.ISetStatus(http.StatusInternalServerError).IJson("time out")
}
}
}