Ensure every HTTP server context has a timeout.

Code that uses http.NewRequestWithContext will see the same deadline.
This commit is contained in:
Tommie Gannert 2021-09-27 11:36:02 +02:00
parent a53c9300aa
commit 1d6501ae30

View file

@ -92,6 +92,7 @@ type BaseDendrite struct {
const NoListener = ""
const HTTPServerTimeout = time.Minute * 5
const HTTPServerRequestTimeout = HTTPServerTimeout
const HTTPClientTimeout = time.Second * 30
type BaseDendriteOptions int
@ -384,6 +385,7 @@ func (b *BaseDendrite) SetupAndServeHTTP(
externalAddr, _ := externalHTTPAddr.Address()
externalRouter := mux.NewRouter().SkipClean(true).UseEncodedPath()
externalRouter.Use(timeoutMiddleware)
internalRouter := externalRouter
externalServ := &http.Server{
@ -521,6 +523,15 @@ func (b *BaseDendrite) SetupAndServeHTTP(
logrus.Infof("Stopped HTTP listeners")
}
// timeoutMiddleware is a Gorilla middleware that adds a timeout to all request contexts.
func timeoutMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), HTTPServerRequestTimeout)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (b *BaseDendrite) WaitForShutdown() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)