github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/server/timeout.go (about) 1 package server 2 3 import ( 4 "context" 5 "github.com/gin-gonic/gin" 6 "net/http" 7 "time" 8 ) 9 10 func Timeout(timeout time.Duration) gin.HandlerFunc { 11 return func(c *gin.Context) { 12 ctx, cancel := context.WithTimeout(c.Request.Context(), timeout) 13 defer func() { 14 if ctx.Err() == context.DeadlineExceeded { 15 c.Writer.WriteHeader(http.StatusGatewayTimeout) 16 c.Abort() 17 } 18 cancel() 19 }() 20 c.Request = c.Request.WithContext(ctx) 21 c.Next() 22 } 23 }