Documentation
¶
Overview ¶
Package httpserver provides a Server that wraps net/http.Server with sane defaults and graceful shutdown support.
Creating a server ¶
Build a Server with New, passing a fully configured handler (e.g. a router). The server owns no routing logic of its own:
srv, err := httpserver.New(
httpserver.WithHandler(router),
httpserver.WithPort(8080),
)
if err != nil {
return err
}
WithHandler is the only required option. WithPort, WithReadTimeout, WithWriteTimeout and WithIdleTimeout override the package defaults.
Running and stopping ¶
Start blocks until the server stops, so run it in a goroutine and wait for a shutdown signal:
go func() {
if err := srv.Start(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatal(err)
}
Shutdown drains active connections before returning, giving in-flight requests a chance to complete within the provided context's deadline.
Index ¶
- type Option
- func WithHandler(h http.Handler) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithPort(port int) Option
- func WithReadHeaderTimeout(d time.Duration) Option
- func WithReadTimeout(d time.Duration) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithWriteTimeout(d time.Duration) Option
- type Server
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(*options)
Option configures a Server.
func WithHandler ¶
WithHandler sets the HTTP handler for the server. Pass a fully configured Router here; the server owns no routing logic.
func WithIdleTimeout ¶
WithIdleTimeout sets the HTTP idle timeout.
func WithReadHeaderTimeout ¶
WithReadHeaderTimeout sets the maximum duration for reading request headers. Setting this protects against slow-header attacks (e.g. Slowloris).
func WithReadTimeout ¶
WithReadTimeout sets the HTTP read timeout.
func WithShutdownTimeout ¶
WithShutdownTimeout sets how long Run waits for active connections to drain during a graceful shutdown before giving up.
func WithWriteTimeout ¶
WithWriteTimeout sets the HTTP write timeout.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps net/http.Server with lifecycle helpers.
func New ¶
New creates a Server with the given options. Returns an error if required options are missing or invalid.
func (*Server) Run ¶
Run starts the server and blocks until ctx is cancelled, then performs a graceful shutdown bounded by the configured shutdown timeout (see WithShutdownTimeout). It returns nil on a clean shutdown, or the first error encountered from either Start or Shutdown.