Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 22, 2023 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/e5a37733801dffff19acf7b5a756f3ac to your computer and use it in GitHub Desktop.
Save ostretsov/e5a37733801dffff19acf7b5a756f3ac to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
)
func Example_limitHandlerExecutionTime() {
heavyHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(1 * time.Hour)
})
handler := http.TimeoutHandler(heavyHandler, 100*time.Millisecond, "timeout")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
handler.ServeHTTP(w, req)
fmt.Println("status code:", w.Code)
fmt.Println("response body:", w.Body.String())
// Output:
// status code: 503
// response body: timeout
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment