Package server implements a customizable HTTP server.

Index

ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe starts an HTTP server with a given address and handler. The handler is typically nil, which means to use DefaultServeMux.

The server listens on the TCP network address addr. It then calls Serve with handler to handle requests on incoming connections.

ListenAndServe always returns a non-nil error. Close and shutdown are alternatives to stop ListenAndServe.

ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS starts an HTTP server with a given address and handler, which listens on the TLS network address addr.

The handler is typically nil, which means to use DefaultServeMux. The certFile and keyFile parameters are the paths to the TLS certificate and key.

If Shutdown is called, ListenAndServeTLS will exit.

Server

type Server struct { ... }

A Server defines parameters for running an HTTP server.

Fields

Server.Serve

func (srv *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the listener l, creating a service goroutine for each. The service goroutines read requests and then call the handler to reply to them. Serve always returns a non-nil error.

Server.ServeTLS

func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming connections on the listener l, creating a service goroutine for each. The service goroutines read requests and then call the handler to reply to them. ServeTLS always returns a non-nil error.

CertFile and keyFile are the paths to the TLS certificate and private key file.

Server.Shutdown

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. It stops accepting new connections and waits for existing connections to finish their work. If the provided context expires before the shutdown completes, Shutdown returns the context's error. Otherwise, it returns any error encountered during shutdown.

Server.Close

func (srv *Server) Close() error

Close closes all active network listeners and any idle connections. It is a shortcut for Shutdown with a nil context.

Server.CloseIdleConnections

func (srv *Server) CloseIdleConnections()

CloseIdleConnections closes all connections that are idle. An idle connection is one that has no pending read or write operations.

Server.ConnContext

func (srv *Server) ConnContext(ctx context.Context) context.Context

ConnContext returns a context that is extended from the Server's BaseContext with the connection's local and remote addresses. This method is called on each accepted connection.

Other Server Fields and Methods

This section provides brief descriptions of other important fields and methods of the `Server` struct.