httpserver

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 13 Imported by: 0

README

httpserver

A small HTTP server wrapper for Go with Kubernetes-native health probes and graceful shutdown. It wraps net/http.Server, adds /livez and /readyz endpoints, and drains connections cleanly on SIGINT/SIGTERM.

The server is written in Lisette (in src/) and compiled to Go. The generated Go package lives at the repo root, so other Go projects use it like any normal library.

Note: this library does not handle routing. Bring your own router (chi, gorilla/mux, http.ServeMux, …) and pass it via WithHandler.

Install

go get github.com/banan-tech/httpserver

Quick start

package main

import (
	"net/http"

	"github.com/banan-tech/httpserver"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World"))
	})

	srv := httpserver.New([]httpserver.ServerOption{
		httpserver.WithHandler(mux),
		httpserver.WithAddr(":8080"),
	})

	// Run blocks until SIGINT/SIGTERM, then shuts down gracefully.
	if err := srv.Run(); err != nil {
		panic(err)
	}
}

Endpoints

Registered automatically unless WithoutDefaultProbes() is used. The probe paths default to /livez and /readyz and are configurable via WithLivenessPath / WithReadinessPath. Probes are mounted directly on the internal mux, so they never pass through (and are never logged by) the handler given to WithHandler:

Path Purpose
/livez Liveness — static 200 while the process can serve. No dependency checks (restart only).
/readyz Readiness — 200 when ready and all checks pass; 503 while shutting down or on failure.
/_metrics Only if WithMetricsHandler is set (e.g. Prometheus).
/ Your handler, if provided via WithHandler.

A failing readiness check returns 503 with a JSON body naming the check:

{ "failed_check": "db", "error": "connection refused" }

Options

Pass any of these to New:

Option Default Description
WithAddr(addr) :8080 Listen address.
WithPortFromEnv() Use :$PORT if PORT is set (applied before options).
WithHandler(h) Root handler mounted at /.
WithMetricsHandler(h) Handler mounted at /_metrics.
WithReadinessCheck(name, fn) Register a named dependency check for /readyz (call once per dependency).
WithoutDefaultProbes() off Disable the built-in liveness and readiness probes.
WithLivenessPath(path) /livez Path the liveness probe is mounted at.
WithReadinessPath(path) /readyz Path the readiness probe is mounted at.
WithLogger(l) JSON Structured *slog.Logger.
WithReadHeaderTimeout(d) 5s Header read deadline (Slowloris protection).
WithReadTimeout(d) 15s Full request read deadline.
WithWriteTimeout(d) 70s Response write deadline.
WithIdleTimeout(d) 90s Keep-alive idle timeout.
WithShutdownTimeout(d) 15s Graceful drain deadline.
WithShutdownHook(fn) Run during shutdown, after connections drain.
Readiness checks
srv := httpserver.New([]httpserver.ServerOption{
	httpserver.WithHandler(mux),
	httpserver.WithReadinessCheck("db", func(ctx context.Context) error {
		return db.PingContext(ctx)
	}),
})

Graceful shutdown

On SIGINT/SIGTERM, Run flips the readiness probe to 503 (so Kubernetes stops routing new traffic), then drains in-flight requests within ShutdownTimeout before running any shutdown hooks and exiting.

Keep ShutdownTimeout below the pod's terminationGracePeriodSeconds, or SIGKILL fires before the drain finishes. Default: 15s < 30s (the Kubernetes default).

Server API

Method Description
New(opts) Build a server from options.
Run() Serve, blocking until a signal, then shut down gracefully.
Start() Serve, blocking (no signal handling). A clean stop returns nil.
Shutdown(ctx) Drain connections within the shutdown timeout, then run hooks.
Handler() The root http.Handler, handy for httptest.

Development

The source of truth is the Lisette code in src/. The root .go files are generated — do not edit them by hand.

lis run            # run the example (src/main.lis)
lis check          # type-check
make emit          # compile src/ to Go and emit the package into the repo root

Documentation

Index

Constants

View Source
const CONTENT_TYPE string = "Content-Type"
View Source
const CONTENT_TYPE_JSON string = "application/json"
View Source
const CONTENT_TYPE_PLAIN string = "text/plain; charset=utf-8"

Variables

This section is empty.

Functions

func DefaultLogger

func DefaultLogger() *slog.Logger

Types

type CheckFunc

type CheckFunc func(context.Context) error

type Config

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

type NamedCheck

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

type Server

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

func New

func New(options []ServerOption) *Server

func (Server) Handler

func (s Server) Handler() http.Handler

func (*Server) Run

func (s *Server) Run() error

func (*Server) Shutdown

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

func (*Server) Start

func (s *Server) Start() error

type ServerOption

type ServerOption func(*Config)

func WithAddr

func WithAddr(addr string) ServerOption

func WithHandler

func WithHandler(h http.Handler) ServerOption

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) ServerOption

func WithLivenessPath

func WithLivenessPath(path string) ServerOption

func WithLogger

func WithLogger(logger *slog.Logger) ServerOption

func WithMetricsHandler

func WithMetricsHandler(h http.Handler) ServerOption

func WithPortFromEnv

func WithPortFromEnv() ServerOption

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) ServerOption

func WithReadTimeout

func WithReadTimeout(d time.Duration) ServerOption

func WithReadinessCheck

func WithReadinessCheck(name string, check CheckFunc) ServerOption

func WithReadinessPath

func WithReadinessPath(path string) ServerOption

func WithShutdownHook

func WithShutdownHook(hook ShutdownHook) ServerOption

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) ServerOption

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ServerOption

func WithoutDefaultProbes

func WithoutDefaultProbes() ServerOption

type ShutdownHook

type ShutdownHook func(context.Context) error

Jump to

Keyboard shortcuts

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