Go Reference ยท Networking and the Web
Go http.Server type
Reference for Go http.Server: address, handler, read and write timeouts, header limits, ListenAndServe, Serve with a listener, Shutdown and ErrServerClosed.
http.Server describes an HTTP server: where it listens, which handler answers, and how patient it is with slow or misbehaving clients. The shortcut http.ListenAndServe builds one with no timeouts at all, so a real service should create its own Server value and set them.
A server also knows how to stop politely. Shutdown closes the listeners, waits for active requests to finish and then returns, which lets you deploy without cutting off clients.
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
err := srv.ListenAndServe()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Server struct { Addr string Handler Handler TLSConfig *tls.Config ReadTimeout time.Duration ReadHeaderTimeout time.Duration WriteTimeout time.Duration IdleTimeout time.Duration MaxHeaderBytes int ErrorLog *log.Logger BaseContext func(net.Listener) context.Context ConnState func(net.Conn, ConnState) // ... more fields } func (srv *Server) ListenAndServe() error func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error func (srv *Server) Serve(l net.Listener) error func (srv *Server) Shutdown(ctx context.Context) error func (srv *Server) Close() error func (srv *Server) RegisterOnShutdown(f func()) func (srv *Server) SetKeepAlivesEnabled(v bool)
| Field | Description |
|---|---|
Addr |
host:port to listen on. Empty means :http (port 80). |
Handler |
The root handler. nil means http.DefaultServeMux. |
ReadHeaderTimeout |
Time allowed to read the request line and headers. Defends against slow-header clients. |
ReadTimeout |
Time allowed to read the entire request, including the body. |
WriteTimeout |
Time from the end of the request header read to the end of the response write. |
IdleTimeout |
How long to keep an idle keep-alive connection. If zero, ReadTimeout is used. |
MaxHeaderBytes |
Limit for request headers. 0 means 1 MB. |
BaseContext |
Supplies the root context for all requests, useful to tie requests to a shutdown signal. |
Returns: ListenAndServe and Serve always return a non-nil error. After Shutdown or Close that error is http.ErrServerClosed.
Errors and edge cases:
Shutdownreturns the context's error if the deadline passes before all requests finish; remaining requests keep running unless you then callClose.Shutdowndoes not wait for hijacked connections (WebSockets). UseRegisterOnShutdownto tell them to stop.- A zero timeout means no limit. The defaults leave the server open to slow-client attacks.
ListenAndServefails with an "address already in use" error if the port is taken.
Usage notes
- Set at least
ReadHeaderTimeout. It is the cheapest protection against slowloris-style clients and costs nothing for normal traffic. WriteTimeoutapplies to the whole response, so it also limits streaming and downloads. Per-request control:http.NewResponseController(w).SetWriteDeadline(...).- Graceful shutdown recipe: run
ListenAndServein a goroutine; wait for SIGINT/SIGTERM withsignal.NotifyContext; callShutdownwith a timeout context; treatErrServerClosedas success. - Listen yourself (
net.Listen+Serve) when you need to know the chosen port (:0) or to take a socket from the supervisor. - Server errors in handlers (panics, connection errors) go to
ErrorLog; set it to your logger. - TLS:
ListenAndServeTLSenables HTTP/2 automatically. Without TLS, HTTP/2 is not offered (except h2c, which needs extra setup). - Do not call
ListenAndServetwice on the sameServerafter shutdown; create a new one.