httpserver

package
v0.0.0-...-f1ec9a5 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

httpserver

httpserver runs composable net/http servers with common lifecycle defaults and small helpers for Connect services.

For ordinary Adiom services, prefer httpapp. Use httpserver directly when a service needs custom mux assembly or lifecycle behavior.

The package does not own routing. Build a normal http.ServeMux, mount regular HTTP handlers, Connect handlers, SPA handlers, redirects, and middleware in the application, then pass the final handler to Server.Run.

Usage

ctx, stop := httpserver.SignalContext(context.Background())
defer stop()

mux := http.NewServeMux()

httpserver.RegisterHealth(mux, httpserver.Health{
	Enabled: true,
})

path, handler := appv1connect.NewAppServiceHandler(api)
services := []httpserver.ConnectService{
	httpserver.Connect(appv1connect.AppServiceName, path, auth.HTTPMiddleware(handler)),
}
httpserver.RegisterConnect(mux, services...)

if cfg.Reflection {
	httpserver.RegisterReflection(mux, httpserver.ServiceNames(services...)...)
}

mux.Handle("/admin/", http.StripPrefix("/admin/", spa.DirHandler(cfg.WebDistDir)))

return httpserver.Server{
	Handler: cors(cfg.CORSOrigin, mux),
}.Run(ctx)

Lifecycle

Server.Run:

  • listens on Addr, or :8080 when Addr is empty
  • serves Handler
  • enables HTTP/1 and unencrypted HTTP/2 by default
  • enables HTTP/1 and TLS HTTP/2 when TLS is configured
  • shuts down gracefully when the context is canceled
  • treats http.ErrServerClosed as a clean stop

Defaults:

  • Addr: :8080
  • ReadHeaderTimeout: 5s
  • IdleTimeout: 75s
  • ShutdownTimeout: 10s

Use SignalContext when a process should stop on SIGINT or SIGTERM.

TLS is optional. Most in-cluster services should terminate TLS at the gateway or service mesh. For services that need to serve TLS directly, configure either certificate files or a custom TLS config:

return httpserver.Server{
	Handler:     mux,
	TLSCertFile: "/var/run/tls/tls.crt",
	TLSKeyFile:  "/var/run/tls/tls.key",
}.Run(ctx)
return httpserver.Server{
	Handler:   mux,
	TLSConfig: tlsConfig,
}.Run(ctx)

Health

Health uses the standard gRPC health service only. No /healthz HTTP mirror is registered by this package.

The simplest Kubernetes setup uses the standard gRPC health service labels:

livenessProbe:
  grpc:
    port: 8080
    service: liveness
readinessProbe:
  grpc:
    port: 8080
    service: readiness

liveness and readiness report serving unless checks are configured and one fails. With no checks, both are noop-ish and return serving. The empty service name reports readiness.

Add dependency checks only when readiness should depend on something external:

httpserver.RegisterHealth(mux, httpserver.Health{
	Enabled: true,
	ReadinessChecks: []httpserver.Check{
		httpserver.ReadinessCheck(db.Ping),
	},
})

Kubernetes still probes service: readiness; it does not know or care that Postgres is one of the checks behind that readiness result.

Prefer readiness checks for dependencies. Add liveness checks only for concrete stuck-process conditions that should restart the pod.

Register health directly on the mux before applying application auth middleware to service handlers, so kubelet probes do not need app credentials.

Reflection

Connect reflection is explicit:

httpserver.RegisterReflection(mux, httpserver.ServiceNames(services...)...)

Do not enable reflection by default for public surfaces.

Documentation

Index

Constants

View Source
const (
	// LivenessService is the Kubernetes gRPC health service label for liveness.
	LivenessService = "liveness"
	// ReadinessService is the Kubernetes gRPC health service label for readiness.
	ReadinessService = "readiness"
)
View Source
const (
	// DefaultAddr is the default listen address for internal services.
	DefaultAddr = ":8080"
)

Variables

This section is empty.

Functions

func RegisterConnect

func RegisterConnect(mux *http.ServeMux, services ...ConnectService)

RegisterConnect mounts Connect services on mux.

func RegisterHealth

func RegisterHealth(mux *http.ServeMux, health Health)

RegisterHealth mounts the standard gRPC health service on mux.

func RegisterReflection

func RegisterReflection(mux *http.ServeMux, serviceNames ...string)

RegisterReflection mounts explicit Connect reflection handlers on mux.

func ServiceNames

func ServiceNames(services ...ConnectService) []string

ServiceNames returns the service names for registration with reflection or health.

func SignalContext

func SignalContext(parent context.Context) (context.Context, context.CancelFunc)

SignalContext returns a context canceled on SIGINT or SIGTERM.

Types

type Check

type Check func(context.Context) error

Check is a health dependency check.

func LivenessCheck

func LivenessCheck(fn func(context.Context) error) Check

LivenessCheck adapts fn into a liveness check.

func ReadinessCheck

func ReadinessCheck(fn func(context.Context) error) Check

ReadinessCheck adapts fn into a readiness check.

type ConnectService

type ConnectService struct {
	Name    string
	Path    string
	Handler http.Handler
}

ConnectService describes a generated Connect handler mounted on an HTTP mux.

func Connect

func Connect(name, path string, handler http.Handler) ConnectService

Connect builds a ConnectService from a generated service name, path, and handler.

type Health

type Health struct {
	Enabled         bool
	LivenessChecks  []Check
	ReadinessChecks []Check
	ServiceNames    []string
}

Health configures the standard gRPC health service.

type Protocols

type Protocols int

Protocols selects the HTTP protocols accepted by a server.

const (
	// ProtocolsInternalCleartext serves HTTP/1 and unencrypted HTTP/2.
	ProtocolsInternalCleartext Protocols = iota
	// ProtocolsTLS serves HTTP/1 and HTTP/2 over TLS.
	ProtocolsTLS
	// ProtocolsHTTP1Only serves only HTTP/1.
	ProtocolsHTTP1Only
)

type Server

type Server struct {
	Addr              string
	Handler           http.Handler
	ReadHeaderTimeout time.Duration
	IdleTimeout       time.Duration
	ShutdownTimeout   time.Duration
	Protocols         Protocols
	TLSConfig         *tls.Config
	TLSCertFile       string
	TLSKeyFile        string
	Logger            *slog.Logger
	OnShutdown        func()
}

Server runs an http.Handler with common lifecycle defaults.

func (Server) Run

func (s Server) Run(ctx context.Context) error

Run starts the server and gracefully shuts it down when ctx is canceled.

Jump to

Keyboard shortcuts

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