Skip to content
This repository has been archived by the owner on Jul 11, 2024. It is now read-only.

Commit

Permalink
Ensure every HTTP server context has a timeout.
Browse files Browse the repository at this point in the history
Code that uses http.NewRequestWithContext will see the same deadline.
  • Loading branch information
tommie authored and samip5 committed Jan 6, 2023
1 parent ed497aa commit 434dfae
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions setup/base/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ type BaseDendrite struct {
const NoListener = ""

const HTTPServerTimeout = time.Minute * 5
const HTTPServerRequestTimeout = HTTPServerTimeout
const HTTPClientTimeout = time.Second * 30

type BaseDendriteOptions int
Expand Down Expand Up @@ -426,6 +427,7 @@ func (b *BaseDendrite) SetupAndServeHTTP(
externalAddr, _ := externalHTTPAddr.Address()

externalRouter := mux.NewRouter().SkipClean(true).UseEncodedPath()
externalRouter.Use(timeoutMiddleware)
internalRouter := externalRouter

externalServ := &http.Server{
Expand Down Expand Up @@ -571,6 +573,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)
Expand Down

0 comments on commit 434dfae

Please sign in to comment.