go-web/framework/middlewares/timeout.go

47 lines
818 B
Go
Raw Permalink Normal View History

package middleware
import (
"context"
"log"
"net/http"
"time"
2024-09-28 09:13:18 +00:00
"github.com/gin-gonic/gin"
)
2024-09-28 09:13:18 +00:00
func Timeout(d time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
finish := make(chan struct{}, 1)
panicChan := make(chan interface{}, 1)
2024-09-28 09:13:18 +00:00
durationCtx, cancel := context.WithTimeout(c.Request.Context(), d)
defer cancel()
go func() {
// Handle panic
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
// Run the next middleware or the business logic
c.Next()
finish <- struct{}{}
}()
select {
case p := <-panicChan:
// panic
log.Println(p)
2024-09-28 09:13:18 +00:00
c.Status(http.StatusInternalServerError)
case <-finish:
// finish normally
log.Println("finish")
case <-durationCtx.Done():
2024-09-28 09:13:18 +00:00
c.JSON(http.StatusRequestTimeout, "time out")
}
}
}