CptJero
CptJero

Reputation: 211

How to implement server side timeouts? (Confused about http.Server timeouts)

I'm trying to implement server-side timeouts for my service. If the request takes longer than X seconds, the server should return 503 Service Unavailable.

I know that this can easily be accomplished by wrapping all of my endpoints in http.TimeoutHandler, but I'm confused why this isn't being done automatically by the Timeout fields of http.Server

Here is a trivial example that I am using for testing. If I cURL or POSTman this server, it hangs forever, rather than the 5 seconds I expect.

package main

import (
    "net/http"
    "time"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/timeouttest", func(_ http.ResponseWriter, _ *http.Request) {
        // busy infinite loop
        // for { _ = struct {}{}}

        // non-busy infinite loop
        select {}
    })
    srv := &http.Server{
        Addr:              "localhost:5000",
        Handler:           mux,
        ReadTimeout:       5 * time.Second,
        ReadHeaderTimeout: 5 * time.Second,
        WriteTimeout:      5 * time.Second,
        IdleTimeout:       90 * time.Second,
    }
    srv.ListenAndServe()
}

EDIT: forgot to link some Cloudflare articles that I have been using as inspiration. complete guide to golang http timeouts so you want to expose go on the internet

Upvotes: 5

Views: 1995

Answers (1)

CptJero
CptJero

Reputation: 211

The answer is to use http.TimeoutHandler. I misunderstood the purpose of the http.Server Timeout fields.

Upvotes: 1

Related Questions