server

package
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package server manages the HTTP server lifecycle with graceful shutdown.

It wraps net/http.Server and handles OS signal interception (SIGINT, SIGTERM), in-flight request draining, and ordered cleanup of external resources.

Basic usage:

srv := server.New(mux, server.WithHost(":3000"))
if err := srv.Run(); err != nil {
	log.Fatal(err)
}

Registering shutdown hooks:

srv := server.New(mux,
	server.WithShutdownFunc(func(ctx context.Context) error {
		return db.Close()
	}),
)

Index

Examples

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 WithHost

func WithHost(host string) Option

WithHost sets the host address the server listens on. Default is ":8080".

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled. Default is 120s.

func WithLogger

func WithLogger(log *slog.Logger) Option

WithLogger sets the logger used for server lifecycle events. Default is slog.Default().

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets the maximum duration for reading the entire request, including the body. Default is 5s.

func WithServer

func WithServer(srv *http.Server) Option

WithServer injects an existing http.Server as the base configuration. Any other options applied after this one override the corresponding fields on the provided server.

func WithShutdownFunc

func WithShutdownFunc(fn func(ctx context.Context) error) Option

WithShutdownFunc registers a function to call during graceful shutdown, before the HTTP server is stopped. Multiple shutdown functions are called in the order they were registered.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/adamwoolhether/httper/web/server"
)

func main() {
	cleanup := func(ctx context.Context) error {
		fmt.Println("closing database")
		return nil
	}

	mux := http.NewServeMux()
	srv := server.New(mux,
		server.WithShutdownFunc(cleanup),
	)

	// Simulate a graceful shutdown instead of calling srv.Run(),
	// which blocks on OS signals.
	if err := srv.Shutdown(context.Background()); err != nil {
		fmt.Println("shutdown error:", err)
		return
	}

	fmt.Println("shutdown complete")
}
Output:
closing database
shutdown complete

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout sets the maximum duration Server.Run waits for in-flight requests to complete after receiving a shutdown signal. Default is 20s. Callers of Server.Shutdown control the deadline via context instead.

func WithTLS

func WithTLS(certFile, keyFile string) Option

WithTLS configures the server to use TLS with the given certificate and key files. When set, the server calls ListenAndServeTLS instead of ListenAndServe.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/adamwoolhether/httper/web/server"
)

func main() {
	srv := server.New(http.NewServeMux(),
		server.WithHost(":8443"),
		server.WithTLS("cert.pem", "key.pem"),
	)

	_ = srv

	fmt.Println("TLS configured")
}
Output:
TLS configured

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout sets the maximum duration before timing out writes of the response. Default is 10s.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server wraps an http.Server with signal-driven graceful shutdown.

func New

func New(handler http.Handler, opts ...Option) *Server

New creates a Server for the given handler. A default host of ":8080", sensible timeouts, and the default slog logger are used unless overridden via options.

Example
package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"time"

	"github.com/adamwoolhether/httper/web/server"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "hello")
	})

	srv := server.New(mux,
		server.WithHost(":3000"),
		server.WithReadTimeout(10*time.Second),
		server.WithLogger(slog.Default()),
	)

	_ = srv // srv.Run() blocks until signal

	fmt.Println("server configured")
}
Output:
server configured

func (*Server) Run

func (s *Server) Run() error

Run starts the HTTP server and blocks until a SIGINT or SIGTERM signal is received, then performs a graceful shutdown. It returns nil on clean shutdown or an error if the server fails to start or shut down.

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server. It first runs any registered shutdown functions in order, then drains in-flight requests. Callers should set a deadline on ctx to bound how long shutdown may take.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL