httpx

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 26 Imported by: 6 modules, 6 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

go-backend-http

HTTP server foundation for Go services on the standard library's net/http and ServeMux. Part of the go-backend-* family. Import as httpx.

go get github.com/ahmedbaig/go-backend-http

What New(...).Handler() gives you

Every request goes through, in order:

  1. Request and correlation IDs: X-Request-ID and X-Correlation-ID are taken from the request (when safe) or generated as UUIDv7, echoed on the response, stored on the context and added to every log line.
  2. Panic recovery: a panic becomes a 500 error response and an error log with the stack.
  3. Access log: one line per request, POST /api/v1/items/7 201 12ms, with method, path, matched route, status, bytes and duration fields. Health and metrics endpoints are skipped.
  4. Metrics: from go-backend-monitoring, labelled by matched route.
  5. Security headers: nosniff, DENY framing, no referrer, a strict CSP, optional HSTS.
  6. Optional CORS, error reporter (Sentry or similar), body size limit, request timeout and your own middleware.

Built-in routes: GET /healthp (full probe state), GET /healthz (liveness), GET /readyz (200 only when stable), GET /metrics, optional static files. Anything unmatched gets a 404 error response, optionally rate-limited per client IP to slow down scanners.

Usage

app := httpx.New(httpx.Options{
	Name:           "my-app",
	Environment:    cfg.Environment,
	Logger:         log.Logger,
	RequestTimeout: 30 * time.Second,
	RateLimit:      &httpx.RateLimitOptions{Requests: 100, Window: 15 * time.Minute},
})

v1 := app.Group("/api/v1", requireUser)
v1.Get("/items/{id}", httpx.Handle(items.Get))
v1.Post("/items", httpx.Handle(items.Create))

app.OnShutdown(func(ctx context.Context) error { return db.Close() })
if err := app.Run(ctx, ":8080"); err != nil {
	log.Error("server stopped", logging.Err(err))
}

Run serves until SIGINT/SIGTERM or ctx is cancelled, then drains in-flight requests, stops the probes and runs the shutdown hooks in reverse order.

Handlers

httpx.Handle turns a typed function into a handler. It binds and validates the request, calls your function and writes JSON.

type CreateItem struct {
	ShopID string `path:"shopId" validate:"required"`
	Name   string `json:"name" validate:"required,min=2"`
	DryRun bool   `query:"dryRun"`
}

func (s *Service) Create(ctx context.Context, in CreateItem) (Item, error) { ... }
  • json:"..." fields come from the body (unknown fields rejected, 10 MB limit), query:"..." from the query string (repeat or comma-separate for slices), path:"..." from {wildcards}.
  • validate:"..." uses go-playground/validator; failures name the field by its JSON/query/path name.
  • Return a value with a StatusCode() int method to change the status (e.g. 201).
  • For full control, write httpx.HandlerFunc(func(w, r) error); a returned error becomes the error response.

Errors

Return httpx.E(code) (optionally .WithMessage, .WithCustomerActions, .WithSupportActions, .WithFields, .Wrap(cause)). Every error response has the same shape:

{
  "requestId": "0193...",
  "correlationId": "0193...",
  "errors": [{
    "code": "E400-2",
    "message": "The request failed validation",
    "customerActions": ["Correct the highlighted fields"],
    "fields": [{ "field": "name", "rule": "min", "message": "must be at least 2" }]
  }]
}

Built-in codes cover 400 (E400-1 bad request, E400-2 validation, E400-3 invalid JSON), 401, 403, 404 (E404-1 resource, E404-2 route), 405, 408, 409, 410, 413, 415, 429, 500, 502, 503 and 504. Add your own with httpx.Register("E422-1", httpx.Definition{...}). Any error that isn't an *httpx.Error becomes E500-1: the client gets a generic message, the real error is logged with the request ID. A request that runs past its deadline becomes E408.

Auth

The gateway authenticates and passes the user as JSON in X-User (go-backend-types types.User).

v1 := app.Group("/api/v1", httpx.RequireUser())
v1.Get("/admin/stats", h, httpx.RequireRole("admin"))
v1.Get("/beta", h, httpx.RequireFeature("beta"))

u, err := httpx.User(ctx)   // 401 error if there is no user

RequireUser returns E401-1 when the header is missing or invalid and adds userId to every log line for the request.

Other helpers

RequestID(ctx), CorrelationID(ctx), LoggerFrom(ctx) read request-scoped values
IDs(ctx) request and correlation IDs, pass to client.WithIDs from go-backend-types
NewClient(transport) *http.Client that forwards X-Correlation-ID to downstream services
ClientIP(r, trusted) client address, honouring X-Forwarded-For only from trusted proxies (loopback by default)
OK, Created, NoContent, JSON, WriteError response writers
Chain, RequestIDs, AccessLog, Recover, SecurityHeaders, CORS, RateLimit, Timeout, BodyLimit the middleware, usable on their own

Server-sent events

v1.Get("/events", httpx.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
	s, err := sse.Start(w)
	if err != nil {
		return err
	}
	events := broker.Subscribe(r.Context(), topics, sse.LastEventID(r))
	return sse.Serve(r.Context(), s, events, sse.Options{Heartbeat: 15 * time.Second, Done: app.Draining()})
}))

sse.Start sets the stream headers (including X-Accel-Buffering: no for nginx) and clears the write deadline. Serve writes events, sends : ping comments on the heartbeat, and returns when the client leaves, the channel closes, or the server starts shutting down (app.Draining()), so open streams never hold up a deploy. Requests with Accept: text/event-stream skip the request timeout.

nginx in front needs proxy_buffering off; and a long proxy_read_timeout on the stream location.

httpx.Validate(v) runs the same struct validation as Bind and returns the same field errors, for input that doesn't arrive over HTTP (gRPC, queues).

License

MIT

Documentation

Index

Constants

View Source
const (
	HeaderCorrelationID = "X-Correlation-ID"
	HeaderRequestID     = "X-Request-ID"
)

Variables

View Source
var ErrServerClosed = errors.New("server closed")
View Source
var LoopbackOnly = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("::1/128")}

Functions

func Bind

func Bind[T any](r *http.Request, opts ...BindOption) (T, error)

func Chain

func Chain(h http.Handler, mws ...Middleware) http.Handler

func ClientIP

func ClientIP(r *http.Request, trusted []netip.Prefix) string

func CorrelationID

func CorrelationID(ctx context.Context) string

func Created

func Created(w http.ResponseWriter, v any)

func Handle

func Handle[Req, Res any](fn func(ctx context.Context, req Req) (Res, error), opts ...BindOption) http.Handler

func IDs added in v0.2.0

func IDs(ctx context.Context) (string, string)

func JSON

func JSON(w http.ResponseWriter, status int, v any)

func LoggerFrom

func LoggerFrom(ctx context.Context) *slog.Logger

func NewClient

func NewClient(next http.RoundTripper) *http.Client

func NoContent

func NoContent(w http.ResponseWriter)

func OK

func OK(w http.ResponseWriter, v any)

func PropagatingTransport

func PropagatingTransport(next http.RoundTripper) http.RoundTripper

func Register

func Register(code Code, d Definition)

func RequestID

func RequestID(ctx context.Context) string

func SkipHealth

func SkipHealth(r *http.Request) bool

func User added in v0.2.0

func User(ctx context.Context) (types.User, error)

func Validate added in v0.3.0

func Validate(v any) error

func Validator

func Validator() *validator.Validate

func WithIDs

func WithIDs(ctx context.Context, requestID, correlationID string) context.Context

func WithLogger

func WithLogger(ctx context.Context, l *slog.Logger) context.Context

func WriteError

func WriteError(w http.ResponseWriter, r *http.Request, err error)

Types

type App

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

func New

func New(o Options) *App

func (*App) Draining added in v0.3.0

func (a *App) Draining() <-chan struct{}

func (*App) Group

func (a *App) Group(prefix string, mws ...Middleware) *Group

func (*App) Handle

func (a *App) Handle(pattern string, h http.Handler)

func (*App) HandleFunc

func (a *App) HandleFunc(pattern string, h HandlerFunc)

func (*App) Handler

func (a *App) Handler() http.Handler

func (*App) Logger

func (a *App) Logger() *slog.Logger

func (*App) Metrics

func (a *App) Metrics() *monitoring.Metrics

func (*App) Mux

func (a *App) Mux() *http.ServeMux

func (*App) OnShutdown

func (a *App) OnShutdown(fn func(context.Context) error)

func (*App) Prober

func (a *App) Prober() *monitoring.Prober

func (*App) Run

func (a *App) Run(ctx context.Context, addr string) error

func (*App) Serve

func (a *App) Serve(ctx context.Context, ln net.Listener) error

func (*App) Server

func (a *App) Server(addr string) *http.Server

type BindOption

type BindOption func(*bindOptions)

func AllowUnknownFields

func AllowUnknownFields() BindOption

func MaxBodyBytes

func MaxBodyBytes(n int64) BindOption

func NoBody

func NoBody() BindOption

func SkipValidation

func SkipValidation() BindOption

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	AllowCredentials bool
	MaxAge           time.Duration
}

type Code

type Code string
const (
	CodeBadRequest      Code = "E400-1"
	CodeValidation      Code = "E400-2"
	CodeInvalidJSON     Code = "E400-3"
	CodeUnauthenticated Code = "E401-1"
	CodeSessionExpired  Code = "E401-2"
	CodeForbidden       Code = "E403-1"
	CodeNotFound        Code = "E404-1"
	CodeRouteNotFound   Code = "E404-2"
	CodeMethod          Code = "E405"
	CodeTimeout         Code = "E408"
	CodeConflict        Code = "E409"
	CodeGone            Code = "E410"
	CodeTooLarge        Code = "E413"
	CodeMediaType       Code = "E415"
	CodeRateLimited     Code = "E429"
	CodeInternal        Code = "E500-1"
	CodeBadGateway      Code = "E502"
	CodeUnavailable     Code = "E503"
	CodeGatewayTimeout  Code = "E504"
)

type Definition

type Definition struct {
	Status          int
	Message         string
	CustomerActions []string
	SupportActions  []string
}

func Lookup

func Lookup(code Code) (Definition, bool)

type Envelope

type Envelope struct {
	RequestID     string   `json:"requestId,omitempty"`
	CorrelationID string   `json:"correlationId,omitempty"`
	Errors        []*Error `json:"errors"`
}

type Error

type Error struct {
	Status          int          `json:"-"`
	Code            Code         `json:"code"`
	Message         string       `json:"message"`
	CustomerActions []string     `json:"customerActions,omitempty"`
	SupportActions  []string     `json:"supportActions,omitempty"`
	Fields          []FieldError `json:"fields,omitempty"`
	// contains filtered or unexported fields
}

func AsError

func AsError(err error) *Error

func E

func E(code Code) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) WithCustomerActions

func (e *Error) WithCustomerActions(a ...string) *Error

func (*Error) WithFields

func (e *Error) WithFields(f ...FieldError) *Error

func (*Error) WithMessage

func (e *Error) WithMessage(msg string) *Error

func (*Error) WithSupportActions

func (e *Error) WithSupportActions(a ...string) *Error

func (*Error) Wrap

func (e *Error) Wrap(cause error) *Error

type ErrorReporter

type ErrorReporter func(ctx context.Context, err error, r *http.Request)

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Rule    string `json:"rule"`
	Message string `json:"message"`
}

type Group

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

func (*Group) Delete

func (g *Group) Delete(path string, h http.Handler, mws ...Middleware)

func (*Group) Get

func (g *Group) Get(path string, h http.Handler, mws ...Middleware)

func (*Group) Group

func (g *Group) Group(prefix string, mws ...Middleware) *Group

func (*Group) Handle

func (g *Group) Handle(method, path string, h http.Handler, mws ...Middleware)

func (*Group) Patch

func (g *Group) Patch(path string, h http.Handler, mws ...Middleware)

func (*Group) Post

func (g *Group) Post(path string, h http.Handler, mws ...Middleware)

func (*Group) Put

func (g *Group) Put(path string, h http.Handler, mws ...Middleware)

func (*Group) Use

func (g *Group) Use(mws ...Middleware)

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Middleware

type Middleware func(http.Handler) http.Handler

func AccessLog

func AccessLog(skip func(*http.Request) bool) Middleware

func BodyLimit

func BodyLimit(n int64) Middleware

func CORS

func CORS(o CORSOptions) Middleware

func RateLimit

func RateLimit(o RateLimitOptions) Middleware

func Recover

func Recover() Middleware

func RequestIDs

func RequestIDs(log *slog.Logger) Middleware

func RequireFeature added in v0.2.0

func RequireFeature(feature string) Middleware

func RequireRole added in v0.2.0

func RequireRole(roles ...string) Middleware

func RequireUser added in v0.2.0

func RequireUser() Middleware

func SecurityHeaders

func SecurityHeaders(o SecurityHeadersOptions) Middleware

func Timeout

func Timeout(d time.Duration) Middleware

func WithErrorReporter

func WithErrorReporter(rep ErrorReporter) Middleware

type Options

type Options struct {
	Name            string
	Environment     string
	Logger          *slog.Logger
	Prober          *monitoring.Prober
	Metrics         *monitoring.Metrics
	RequestTimeout  time.Duration
	ShutdownTimeout time.Duration
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	IdleTimeout     time.Duration
	MaxBodyBytes    int64
	CORS            *CORSOptions
	RateLimit       *RateLimitOptions
	Security        SecurityHeadersOptions
	TrustedProxies  []netip.Prefix
	ErrorReporter   ErrorReporter
	Middleware      []Middleware
	StaticDir       string
	StaticPrefix    string
}

type RateLimitOptions

type RateLimitOptions struct {
	Requests int
	Window   time.Duration
	Burst    int
	KeyFunc  func(*http.Request) string
	Skip     func(*http.Request) bool
}

type SecurityHeadersOptions

type SecurityHeadersOptions struct {
	HSTS                  bool
	ContentSecurityPolicy string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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