Documentation
¶
Overview ¶
Package httpserver is the standard-library-idiomatic core of the server kit: a worker.Runnable that serves any http.Handler on its own listener with graceful shutdown.
The seam is net/http's own abstraction, http.Handler — so the handler can be a stdlib *http.ServeMux, the SDK's rest/router, a grpc-gateway runtime.ServeMux, or any third-party router. REST, the gRPC-gateway and the status server (debugsrv) are all just this one brick wrapped around a different handler; register each with a single worker.Group and they start, fail and drain independently, like Lego.
Usage ¶
srv := httpserver.New(httpserver.Config{
Name: "rest-server",
Addr: ":8080",
ShutdownTimeout: 10 * time.Second,
Logger: log,
}, router)
grp := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
grp.Add(srv) // alongside grpcserver.Server, debugsrv.Server, ...
_ = grp.Run(ctx)
Tests and callers that manage their own listener can use Serve instead of Start:
lis, _ := net.Listen("tcp", "localhost:0")
go srv.Serve(lis)
// ... drive lis.Addr(); then srv.Stop(ctx)
Config ¶
Only Addr is required; everything else has a safe default.
- Addr: listen address, e.g. ":8080".
- Name: supervisor/log name (default "http-server"); set it so REST/gateway/ status read distinctly.
- ReadHeaderTimeout: bounds reading request headers (default 5s) against Slowloris-style stalls; a negative value disables it.
- IdleTimeout: bounds an idle keep-alive connection (default 30s); a negative value leaves it to net/http.
- ReadTimeout / WriteTimeout: map to the http.Server fields of the same name; zero leaves each at the net/http default.
- ShutdownTimeout: bounds graceful shutdown when Stop's ctx has no deadline (default 10s). Connections still busy when it runs out are closed.
- Logger: receives start/stop lines; defaults to slog.Default().
- ErrorLog: receives net/http's own errors (TLS handshakes, superfluous WriteHeader); nil uses the standard logger.
Handler returns the served handler, so tests can drive a server through httptest without binding a port.
Example ¶
A service runs the server in a worker group, next to the gRPC and status servers: the group starts them and drains them all on SIGINT or SIGTERM.
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/assanoff/skit/httpserver"
"github.com/assanoff/skit/worker"
)
// hello is the handler the server serves: a router in a service.
func hello() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "hello")
})
return mux
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
srv := httpserver.New(httpserver.Config{
Name: "rest-server",
Addr: ":8080",
Logger: log,
}, hello())
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
grp := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
grp.Add(srv)
if err := grp.Run(ctx); err != nil {
log.ErrorContext(ctx, "run", "err", err)
}
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Addr is the listen address, e.g. ":8080".
Addr string
// Name identifies the server to the supervisor and in logs (default
// "http-server"). Set it so REST/gateway/status read distinctly.
Name string
// ReadHeaderTimeout bounds reading request headers (default 5s) to guard
// against Slowloris-style stalls. Set a negative duration to disable it.
ReadHeaderTimeout time.Duration
// IdleTimeout bounds how long a keep-alive connection waits for its next
// request (default 30s). Set a negative duration to leave it to net/http,
// which then uses ReadTimeout, or no limit when that is zero too.
IdleTimeout time.Duration
// ReadTimeout and WriteTimeout map to the http.Server fields of the same
// name; zero leaves each at the net/http default (no limit).
ReadTimeout time.Duration
WriteTimeout time.Duration
// ShutdownTimeout bounds graceful shutdown when Stop's context carries no
// deadline (default 10s).
ShutdownTimeout time.Duration
// Logger receives start/stop lines; defaults to slog.Default().
Logger *slog.Logger
// ErrorLog receives net/http's own errors — failed TLS handshakes, a
// superfluous WriteHeader, a panic net/http recovered; nil uses the standard
// logger. To keep them in the service log, pass
// slog.NewLogLogger(logger.Handler(), slog.LevelError).
ErrorLog *log.Logger
}
Config configures a Server. Only Addr is required; every other field falls back to a safe default.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server serves an http.Handler on its own listener and implements worker.Runnable (Start/Stop/Name). It is the standard-library-idiomatic core of the server kit: REST, the gRPC-gateway and the status server are all just this brick wrapped around a different http.Handler, so they compose in a single worker.Group.
func New ¶
New wraps h in an *http.Server configured by cfg. The server is not listening until Start (or Serve) is called.
func (*Server) Handler ¶ added in v0.12.0
Handler returns what the server serves, so a test can drive it through httptest without a listener.
func (*Server) Serve ¶
Serve serves on the provided listener until Stop. It is useful for tests (an ephemeral localhost:0 listener) and for callers that manage their own listener. ErrServerClosed is treated as a clean shutdown.
Example ¶
Serve takes a listener of the caller, here an ephemeral port; Stop drains the requests in flight and Serve returns.
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"github.com/assanoff/skit/httpserver"
)
// hello is the handler the server serves: a router in a service.
func hello() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "hello")
})
return mux
}
func main() {
srv := httpserver.New(httpserver.Config{Logger: slog.New(slog.DiscardHandler)}, hello())
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Println(err)
return
}
served := make(chan error, 1)
go func() { served <- srv.Serve(lis) }()
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx,
http.MethodGet, "http://"+lis.Addr().String()+"/hello", nil)
if err != nil {
fmt.Println(err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
return
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
fmt.Println(resp.StatusCode, string(body), err)
fmt.Println(srv.Name(), srv.Stop(ctx), <-served)
}
Output: 200 hello <nil> http-server <nil> <nil>