HTTP Server
Handle web requests and set time limits for reading and writing them.
HTTP is the set of rules web programs use to exchange requests and responses. In Go, a handler is a function that receives one request and writes its response. Create an http.Server directly when you need time limits; the simpler http.ListenAndServe call does not set them.
A ServeMux routes each request to a handler, the function that writes its response, based on the URL path. ReadHeaderTimeout limits how long the server waits for request headers, extra details sent with a request. ReadTimeout limits how long it waits for the full request, WriteTimeout limits how long it writes the response, and IdleTimeout limits how long an unused connection stays open.
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
})
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 60 * time.Second,
}
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}In production
Choose timeouts that allow the requests and responses your program needs. A streaming response sends data over time and may need a longer write limit. During shutdown, server.Shutdown stops new requests and gives handlers already working time to finish. Pass the request context, a value carrying a stop signal, to slow operations so they can stop if the caller disconnects.