Implement timeout middleware by wrapping the http.Handler with a function that creates a context with a deadline and passes it to the wrapped handler.
func TimeoutMiddleware(next http.Handler, timeout time.Duration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
Use it by wrapping your handler: http.ListenAndServe(":8080", TimeoutMiddleware(myHandler, 5*time.Second)).