httpserver

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 15 Imported by: 2 modules, 1 package

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.

Documentation

Overview

Package httpserver provides shared HTTP request infrastructure.

Callers own routing, authentication and server lifetime. Forwarded client addresses never replace the request's transport peer.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CanonicalOrigin

func CanonicalOrigin(value string) (string, error)

CanonicalOrigin validates a configured public origin without exposing raw credentials in errors. It accepts HTTP(S) origins with no credentials, query, fragment or non-root path, lowercases hosts, compresses IPv6, and removes default ports and the trailing slash. Hostnames must be ASCII (use punycode for internationalized names); IPv4 must use canonical dotted-decimal form. Mapped and scoped IPv6 addresses are unsupported. Empty returns "", nil so callers can represent an optional origin; requiredness and HTTPS policy belong to the host.

func ClientIP

func ClientIP(ctx context.Context) string

ClientIP returns the trusted client address resolved by NewHandler, or empty when no shared request middleware populated the context.

func NewHandler

func NewHandler(next http.Handler, opts Options) (http.Handler, error)

NewHandler wraps next with per-request execution trace tasks and trusted metadata and access logging, then optional origin filtering and host checks. ClientIP, Origin and RequestOrigin expose the resolved metadata even for rejected requests. The request's RemoteAddr and Host are never rewritten. Routing, authentication, cross-origin policy, server lifetime and starting execution traces stay with the caller.

func Origin

func Origin(ctx context.Context) string

Origin returns the country code or network label resolved by NewHandler. Empty means origin enrichment was disabled or the address was unknown.

func ParseTrustedProxies

func ParseTrustedProxies(raw []string) ([]netip.Prefix, error)

ParseTrustedProxies parses CIDR prefixes and masks off host bits. An empty list trusts no proxies. It returns no prefixes if any entry is invalid.

func RequestOrigin

func RequestOrigin(ctx context.Context) string

RequestOrigin returns the request's HTTP(S) scheme and authority, using forwarding headers only from TrustedProxies. It is not the Origin header or the configured external URL. Empty means invalid or unavailable metadata.

func ResolveClientIP

func ResolveClientIP(r *http.Request, prefixes []netip.Prefix) string

ResolveClientIP returns the client address for r without changing it. It accepts X-Forwarded-For and X-Real-IP only from a direct peer in prefixes. For X-Forwarded-For it validates the entire chain and returns the rightmost untrusted address. Malformed headers and all-trusted chains use the direct peer. X-Forwarded-For takes precedence over X-Real-IP, including on failure. IPv4-mapped addresses are returned and compared as IPv4. Prefixes should be parsed once at startup with ParseTrustedProxies. A bare IP peer is returned directly without honoring headers. An invalid peer yields "".

func TrustsAddress

func TrustsAddress(addr netip.Addr, trustedProxies []netip.Prefix) bool

TrustsAddress reports whether addr belongs to a configured trusted proxy.

func TrustsPeer

func TrustsPeer(remoteAddr string, trustedProxies []netip.Prefix) bool

TrustsPeer reports whether remoteAddr is the address of a configured trusted proxy. A trusted peer must use the host:port form supplied by net/http.

Types

type AccessLog

type AccessLog struct {
	http.Handler

	Logger *slog.Logger
	// SuccessLevel controls logging for responses below 300. Zero is Info.
	SuccessLevel slog.Level
}

AccessLog wraps an HTTP handler and logs each request after it completes.

It records the response status, transmitted byte count, duration, and hijack state. The ip field uses ClientIP from request context; origin is included only when Origin is nonempty. NewHandler populates this metadata. Responses below 300 use SuccessLevel; all other responses are logged at info level.

func (AccessLog) ServeHTTP

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

ServeHTTP implements http.Handler.

type HostPolicy

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

HostPolicy enforces one public authority and publishes its external URL. Proxy trust belongs to Options.TrustedProxies, not the policy. Only the request middleware may discover an origin; ExternalURL is a read-only view. A policy is shared by one server and its OAuth/redirect consumers.

func NewHostPolicy

func NewHostPolicy(opts HostPolicyOptions) (*HostPolicy, error)

NewHostPolicy validates a configured external URL or enables discovery. Authorities are compared with canonical host spelling and default ports interpreted using the configured public scheme. The configured scheme describes the public URL, not the backend transport: HTTPS termination may forward HTTP to the server.

func (*HostPolicy) ExternalURL

func (s *HostPolicy) ExternalURL() string

ExternalURL returns the configured or discovered public origin, or empty before an automatic policy has accepted its first FQDN request. It never inspects a request or changes policy state.

type HostPolicyOptions

type HostPolicyOptions struct {
	// ExternalURL is the configured HTTP(S) public origin. Empty discovers and
	// locks the origin from the first accepted FQDN request.
	ExternalURL string
	// AllowLocal permits IP addresses and single-label hosts without changing
	// the external URL. Local requests never establish an automatic origin.
	AllowLocal bool
}

HostPolicyOptions selects authority enforcement and external URL discovery.

type Options

type Options struct {
	// TrustedProxies authorizes forwarded client-IP and host/scheme headers.
	// It does not restrict which peers may connect. Empty trusts no proxies.
	// Trusted proxies must replace origin headers with authoritative values.
	// Forwarded or paired X-Forwarded-Host/X-Forwarded-Proto are accepted;
	// malformed or inconsistent trusted origin headers fail the host check.
	// Untrusted peers' forwarding headers are ignored.
	TrustedProxies []netip.Prefix
	// Hosts enables authority enforcement and external URL discovery. Nil allows
	// any host. Proxy trust always comes from TrustedProxies. Rejected
	// authorities return HTTP 403 and are access-logged.
	Hosts *HostPolicy
	GeoIP OriginChecker
	// Logger is required for access logging. Use slog.DiscardHandler to discard logs.
	Logger *slog.Logger
	// SuccessLevel controls logging for responses below 300. Zero is Info.
	SuccessLevel slog.Level
}

Options selects host policies for NewHandler. Immutable after construction.

type OriginChecker

type OriginChecker interface {
	CheckOrigin(clientIP string) (origin string, allowed bool)
}

OriginChecker resolves a client address and optionally restricts its origin. Implementations must support concurrent requests. The optional geoip package supplies MMDB enrichment and named-network allowlists.

Directories

Path Synopsis
Package geoip provides IP origin and country allowlist enforcement.
Package geoip provides IP origin and country allowlist enforcement.
data
Package data defines the on-disk named IP-origin cache.
Package data defines the on-disk named IP-origin cache.

Jump to

Keyboard shortcuts

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