2024-09-24 21:07:42 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-09-24 21:21:48 +00:00
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2024-09-24 21:07:42 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.vinchent.xyz/vinchent/go-web/framework"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Timeout(d time.Duration) framework.ControllerHandler {
|
2024-09-24 21:21:48 +00:00
|
|
|
return func(c *framework.Context) error {
|
|
|
|
finish := make(chan struct{}, 1)
|
|
|
|
panicChan := make(chan interface{}, 1)
|
|
|
|
|
|
|
|
durationCtx, cancel := context.WithTimeout(c.BaseContext(), 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)
|
|
|
|
c.GetResponseWriter().WriteHeader(http.StatusInternalServerError)
|
|
|
|
case <-finish:
|
|
|
|
// finish normally
|
|
|
|
log.Println("finish")
|
|
|
|
case <-durationCtx.Done():
|
|
|
|
c.SetHasTimeout()
|
|
|
|
c.GetResponseWriter().Write([]byte("time out"))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-09-24 21:07:42 +00:00
|
|
|
}
|