httpserver

package module
v0.0.0-...-d4568e1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpserver

Go Reference codecov

HTTP server built on the standard http.ServeMux, with handlers, middlewares and handler groups registered through fx, and OpenTelemetry instrumentation.

go get github.com/go-oryn/oryn/httpserver

Quick start

func main() {
	core.New(
		core.WithConfigFS(configs.FS),
		httpserver.Module,
		httpserver.AsHandler("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintf(w, "hello %s", r.PathValue("name"))
		}),
	).Run(httpserver.Serve())
}

httpserver.Module provides the *http.Server, and httpserver.Serve() starts it with the application.

Handlers

AsHandler registers a handler for a ServeMux pattern: [METHOD ][HOST]/[PATH], with {name} wildcards read with r.PathValue("name").

A handler is either:

  • a value: an http.Handler, or a func(http.ResponseWriter, *http.Request),
  • or a constructor returning one, whose parameters are injected by fx.
type GetUserHandler struct {
	repository *UserRepository
}

func NewGetUserHandler(repository *UserRepository) *GetUserHandler {
	return &GetUserHandler{repository: repository}
}

func (h *GetUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user, err := h.repository.Find(r.Context(), r.PathValue("id"))
	// ...
}

var Module = fx.Options(
	httpserver.AsHandler("GET /users/{id}", NewGetUserHandler),
	httpserver.AsHandler("GET /ping", func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "pong")
	}),
)

Middlewares

A middleware is either:

  • a value: a func(http.Handler) http.Handler (the usual Go middleware signature, so existing middlewares work as is), or an httpserver.Middleware (an interface with Wrap(next http.Handler) http.Handler),
  • or a constructor returning one, whose parameters are injected by fx.

AsMiddleware registers global middlewares, applied to every handler. Middlewares can also be given to a single handler, after its pattern and handler:

func NewAuthMiddleware(verifier *TokenVerifier) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if !verifier.Verify(r) {
				http.Error(w, "unauthorized", http.StatusUnauthorized)

				return
			}

			next.ServeHTTP(w, r)
		})
	}
}

var Module = fx.Options(
	httpserver.AsMiddleware(NewAuthMiddleware),
	httpserver.AsHandler("DELETE /users/{id}", NewDeleteUserHandler, NewAuditMiddleware),
)

Middlewares run in registration order, the first one being the outermost: global middlewares, then group middlewares (outer groups first), then handler middlewares. They run once the request is routed: r.Pattern and r.PathValue() are available.

Handler groups

AsHandlerGroup registers handlers sharing a path prefix and middlewares. Groups can be nested with WithGroup.

httpserver.AsHandlerGroup("/api/v1",
	httpserver.WithMiddlewares(NewAuthMiddleware),
	httpserver.WithHandler("GET /users", NewListUsersHandler),
	httpserver.WithHandler("POST /users", NewCreateUserHandler, NewAuditMiddleware),
	httpserver.WithGroup("/admin",
		httpserver.WithMiddlewares(NewAdminMiddleware),
		httpserver.WithHandler("GET /stats", NewStatsHandler),
	),
)
Request Middlewares, in order
GET /api/v1/users global, auth
POST /api/v1/users global, auth, audit
GET /api/v1/admin/stats global, auth, admin

The group patterns are relative to the prefix, and cannot have a host. WithMiddlewares applies to all the handlers of the group, wherever it is placed. A group middleware is built once, and shared by the group handlers.

Observability

Every request goes through, from the outermost:

  1. the otelhttp instrumentation: a server span named after the route (GET /users/{id}), with the http.route attribute, and the HTTP server metrics,
  2. the request log: http request, with method, path, route, status, response_size and duration, at error level for 5xx responses and info level otherwise,
  3. the panic recovery: a panic is logged with its stack, and answered with a 500 if nothing was written yet,
  4. the routing, the middlewares and the handler.

Logs are correlated with the request span. Paths matching httpserver.observability.exclude (e.g. health checks) get neither spans, metrics nor request logs.

Configuration

httpserver:
  # Listen address.
  address: ":8080"                # default ":8080"
  # Server timeouts. 0 disables a timeout.
  read_header_timeout: 10s        # default 10s
  read_timeout: 0s                # default 0s
  write_timeout: 0s               # default 0s
  idle_timeout: 2m                # default 2m
  log:
    # Log every request.
    enabled: true                 # default true
  observability:
    # Go regular expressions matched against the request path, excluded from spans, metrics and request logs.
    exclude:                      # default []
      - "^/livez$"
      - "^/readyz$"

Testing

Tests run the application with coretest, and serve requests with the *http.Server handler, without listening on a port:

func TestGetUser(t *testing.T) {
	var (
		server *http.Server
		spans  *tracetest.InMemoryExporter
	)

	coretest.Start(t, core.New(httpserver.Module, users.Module), fx.Populate(&server, &spans))

	recorder := httptest.NewRecorder()
	server.Handler.ServeHTTP(recorder, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/users/42", nil))

	assert.Equal(t, http.StatusOK, recorder.Code)
	spantest.HasSpan(t, spans, spantest.WithName("GET /users/{id}"))
}

To test over the network, set httpserver.address to 127.0.0.1:0 and add httpserver.Serve(): once started, server.Addr is the listening address.

Documentation

Overview

Package httpserver provides an HTTP server built on http.ServeMux, instrumented with OpenTelemetry.

Handlers, middlewares and handler groups are registered with AsHandler, AsMiddleware and AsHandlerGroup, and built by fx with their dependencies. The server is started with Serve:

core.New(
	httpserver.Module,
	httpserver.AsMiddleware(NewAuthMiddleware),
	httpserver.AsHandler("GET /users/{id}", NewGetUserHandler),
).Run(httpserver.Serve())

Index

Constants

View Source
const (
	DefaultAddress           = ":8080"
	DefaultReadHeaderTimeout = 10 * time.Second
	DefaultIdleTimeout       = 2 * time.Minute
)

Defaults of the config keys.

View Source
const ModuleName = "httpserver"

ModuleName is the name of the httpserver fx module.

Variables

Module provides the *http.Server, with the registered handlers and middlewares.

Functions

func AsHandler

func AsHandler(pattern string, handler any, middlewares ...any) fx.Option

AsHandler registers a handler for the http.ServeMux pattern (e.g. "GET /users/{id}"), with optional middlewares applied to this handler only, after the global ones.

The handler is either a value (an http.Handler, or a func(http.ResponseWriter, *http.Request)), or a constructor returning one, whose parameters are injected by fx. Middlewares are described in AsMiddleware.

func AsHandlerGroup

func AsHandlerGroup(prefix string, options ...GroupOption) fx.Option

AsHandlerGroup registers a group of handlers sharing a path prefix (e.g. "/api/v1") and middlewares. The patterns of the group handlers are relative to the prefix: "GET /users" in the group "/api" serves "GET /api/users".

httpserver.AsHandlerGroup("/api",
	httpserver.WithMiddlewares(NewAuthMiddleware),
	httpserver.WithHandler("GET /users", NewListUsersHandler),
	httpserver.WithHandler("POST /users", NewCreateUserHandler, NewAuditMiddleware),
	httpserver.WithGroup("/admin",
		httpserver.WithMiddlewares(NewAdminMiddleware),
		httpserver.WithHandler("GET /stats", NewStatsHandler),
	),
)

func AsMiddleware

func AsMiddleware(middlewares ...any) fx.Option

AsMiddleware registers global middlewares, applied to every handler in registration order: the first registered middleware is the outermost one.

A middleware is either a value (a Middleware, or a func(http.Handler) http.Handler), or a constructor returning one, whose parameters are injected by fx.

func NewServer

func NewServer(params NewServerParams) (*http.Server, error)

NewServer returns the HTTP server. Every request goes through, from the outermost:

  1. the OpenTelemetry instrumentation (spans and metrics), skipped for the excluded paths,
  2. the request logs, unless disabled, and skipped for the excluded paths,
  3. the panic recovery,
  4. the routing, then the global, group and handler middlewares, and the handler.

func Serve

func Serve() fx.Option

Serve starts the HTTP server with the application, on httpserver.address, and shuts it down gracefully when the application stops. Once started, the server Addr is the listening address (useful with port 0). If the server fails, the application is shut down.

Types

type GroupOption

type GroupOption func(*group)

GroupOption configures a handler group, see AsHandlerGroup.

func WithGroup

func WithGroup(prefix string, options ...GroupOption) GroupOption

WithGroup adds a sub group, whose prefix is relative to the group one, and whose handlers also get the group middlewares. See AsHandlerGroup.

func WithHandler

func WithHandler(pattern string, handler any, middlewares ...any) GroupOption

WithHandler adds a handler to the group, with optional middlewares applied to this handler only, after the group middlewares. See AsHandler.

func WithMiddlewares

func WithMiddlewares(middlewares ...any) GroupOption

WithMiddlewares adds middlewares to all the handlers of the group, including its sub groups, wherever the option is placed. They are applied after the global and parent group middlewares.

type Middleware

type Middleware interface {
	Wrap(next http.Handler) http.Handler
}

Middleware wraps a handler, to run code before and after it.

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

MiddlewareFunc is a func(http.Handler) http.Handler Middleware.

func (MiddlewareFunc) Wrap

func (f MiddlewareFunc) Wrap(next http.Handler) http.Handler

Wrap calls f(next).

type NewServerParams

type NewServerParams struct {
	fx.In

	Config         *config.Config
	Logger         *slog.Logger
	TracerProvider trace.TracerProvider
	MeterProvider  metric.MeterProvider
	Propagator     propagation.TextMapPropagator
	Middlewares    []registeredMiddleware `group:"oryn-httpserver-middlewares"`
	Routes         []route                `group:"oryn-httpserver-routes"`
}

NewServerParams are the dependencies of NewServer.

Jump to

Keyboard shortcuts

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