Documentation
¶
Overview ¶
Package http provides an HTTP server and client with built-in support for metrics, authentication, and structured logging.
Example ¶
Example demonstrates encoding and decoding structs to/from HTTP headers.
package main
import (
"fmt"
"log"
dhttp "github.com/dioad/net/http"
)
func main() {
// Define a struct to encode
type RequestMetadata struct {
User string
Session string
Tags []string
}
metadata := RequestMetadata{
User: "user-123",
Session: "session-456",
Tags: []string{"tag1", "tag2", "tag3"},
}
// Configure marshaling with a prefix and struct name
opts := dhttp.HTTPMarshalOptions{
Prefix: "X",
IncludeStructName: true,
}
// Marshal to HTTP header
headers, err := dhttp.MarshalHeader(metadata, opts)
if err != nil {
log.Fatal(err)
}
// Print the headers
fmt.Println("Encoded headers:")
fmt.Printf(" X-Request-Metadata-User: %s\n", headers.Get("X-Request-Metadata-User"))
fmt.Printf(" X-Request-Metadata-Session: %s\n", headers.Get("X-Request-Metadata-Session"))
fmt.Printf(" X-Request-Metadata-Tags: %v\n", headers.Values("X-Request-Metadata-Tags"))
// Unmarshal back to a struct
var decoded RequestMetadata
err = dhttp.UnmarshalHeader(headers, &decoded, opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("\nDecoded struct:\n")
fmt.Printf(" User: %s\n", decoded.User)
fmt.Printf(" Session: %s\n", decoded.Session)
fmt.Printf(" Tags: %v\n", decoded.Tags)
}
Output: Encoded headers: X-Request-Metadata-User: user-123 X-Request-Metadata-Session: session-456 X-Request-Metadata-Tags: [tag1 tag2 tag3] Decoded struct: User: user-123 Session: session-456 Tags: [tag1 tag2 tag3]
Index ¶
- Constants
- Variables
- func CORSAllowLocalhostOrigin(origin string) bool
- func Chain(handler http.Handler, middlewares ...Middleware) http.Handler
- func ClientIPFromContext(ctx context.Context) (string, bool)
- func ClientIPPrincipalFunc(r *http.Request) (string, error)
- func ContextWithClientIP(ctx context.Context, r *http.Request) context.Context
- func CreateHTTPHeaderFromMap(headerMap map[string]string) http.Header
- func GetClientIP(r *http.Request) string
- func MarshalHeader(v any, opts HTTPMarshalOptions) (http.Header, error)
- func MarshalQuery(v any, opts HTTPMarshalOptions) (string, error)
- func MergedHTTPHeader(baseHeaders http.Header, headerMap map[string]string) http.Header
- func NewPersistentCookieStore(config CookieConfig) (*sessions.CookieStore, error)
- func NewSessionCookieStore(config CookieConfig) (*sessions.CookieStore, error)
- func NewUnixSocketClient(path string) *http.Client
- func RequestIDMiddleware(next http.Handler) http.Handler
- func StandardLogger(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger
- func UnmarshalHeader(header http.Header, v any, opts HTTPMarshalOptions) error
- func UnmarshalHeaderFromRequest(req *http.Request, v any, opts HTTPMarshalOptions) error
- func UnmarshalQuery(rawQuery string, v any, opts HTTPMarshalOptions) error
- func UnmarshalQueryFromRequest(req *http.Request, v any, opts HTTPMarshalOptions) error
- func WithPrincipalFunc(getPrincipal PrincipalFunc) func(*RateLimiter)
- func WithRateLimitLogger(logger zerolog.Logger) func(*RateLimiter)
- func WithRateLimitSource(source ratelimit.RateLimitSource) func(*RateLimiter)
- func WithRateLimiterRegistry(reg prometheus.Registerer) func(*RateLimiter)
- func WithStaticRateLimit(requestsPerSecond float64, burst int) func(*RateLimiter)
- type BodySizeLimiter
- type BodySizeLimiterOpt
- type CORSConfig
- type Client
- type ClientConfig
- type ClientIPConfig
- type ClientIPResolver
- type ClientIPResolverOption
- type Config
- type CookieConfig
- type CookieKeyPair
- type EnforceTLSHandler
- type HTTPMarshalOptions
- type HandlerWrapper
- type HealthRegistry
- type Instrument
- type LivenessResource
- type LogLevelSetter
- type MetadataResource
- type MetricSet
- type Middleware
- type OperationalConfig
- type OperationsConfig
- type PrincipalFunc
- type ProxyProtocolPolicy
- type RateLimiter
- type RateLimiterOption
- type ReadinessResource
- type Resource
- type RootResource
- type Server
- func (s *Server) AddHandler(path string, handler http.Handler)
- func (s *Server) AddHandlerFunc(path string, handler http.HandlerFunc)
- func (s *Server) AddHealthSource(name string, source any) error
- func (s *Server) AddResource(pathPrefix string, r Resource, middlewares ...Middleware)
- func (s *Server) AddRootResource(r RootResource)
- func (s *Server) AddStatusStaticMetadataItem(key string, value any)
- func (s *Server) ConfigureTelemetryInstrument(i Instrument)
- func (s *Server) Failed() <-chan error
- func (s *Server) ListenAndServe() error
- func (s *Server) ListenAndServeTLS(tlsConfig *tls.Config) error
- func (s *Server) Live(context.Context) error
- func (s *Server) MetricSet() *MetricSet
- func (s *Server) RegisterOnShutdown(f func())
- func (s *Server) Serve(ln net.Listener) error
- func (s *Server) ServeTLS(ln net.Listener) error
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) Start(ctx context.Context) error
- func (s *Server) Use(middlewares ...Middleware)
- type ServerOption
- func WithCORS(options cors.Options) ServerOption
- func WithComponent(name string) ServerOption
- func WithDebug() ServerOption
- func WithHealth() ServerOption
- func WithLogWriter(w io.Writer) ServerOption
- func WithLogger(l zerolog.Logger) ServerOption
- func WithMetricsGatherers(gatherers ...prometheus.Gatherer) ServerOption
- func WithPrometheusMetrics() ServerOption
- func WithPrometheusRegistry(r prometheus.Registerer) ServerOption
- func WithProxyProtocol(policy ProxyProtocolPolicy) ServerOption
- func WithReadiness(r ReadinessResource) ServerOption
- func WithStatus() ServerOption
- func WithTelemetryInstrument(i Instrument) ServerOption
- type StatusResource
- type StructuredLoggerFormatter
Examples ¶
Constants ¶
const DefaultCORSMaxAge = 24 * time.Hour
DefaultCORSMaxAge is how long browsers may cache a preflight response when CORSConfig does not say.
const (
// DefaultMaxBodyBytes is the default maximum request body size (1MB).
DefaultMaxBodyBytes = 1 * 1024 * 1024
)
const DefaultPersistentCookieMaxAge = 30 * 24 * 60 * 60 // 30 days, in seconds
DefaultPersistentCookieMaxAge is used by NewPersistentCookieStore when CookieConfig.MaxAge is left at its zero value.
const (
// HeaderMarshalTagName is the struct tag name used for marshaling/unmarshaling HTTP headers.
HeaderMarshalTagName = "header"
)
const ManagementAllowNonLoopbackKey = "management-allow-unauthenticated-non-loopback"
ManagementAllowNonLoopbackKey is the setting that acknowledges a management listener bound beyond loopback. OperationsConfig.Check names it in its findings, so every service reports the same key.
const (
// QueryMarshalTagName is the struct tag name used for marshaling/unmarshaling URI query parameters.
QueryMarshalTagName = "query"
)
Variables ¶
var ( // DefaultRequestsPerSecond is the default per-principal request rate // used when NewRateLimiter is not given WithStaticRateLimit. DefaultRequestsPerSecond = float64(10) // DefaultBurst specifies the default maximum burst size for rate limiting. DefaultBurst = 20 )
var ErrNotAHealthSource = errors.New("health source implements none of Live, Ready and Status")
ErrNotAHealthSource is returned by RegisterHealthSource for a value that implements none of LivenessResource, ReadinessResource and StatusResource.
Functions ¶
func CORSAllowLocalhostOrigin ¶ added in v0.50.4
CORSAllowLocalhostOrigin returns true if the given origin is a localhost origin.
func Chain ¶ added in v0.55.0
func Chain(handler http.Handler, middlewares ...Middleware) http.Handler
Chain builds an http.Handler composed of the target handler and the provided middlewares. The middlewares are applied in reverse order so the first middleware in the list is the first to execute.
func ClientIPFromContext ¶ added in v0.54.0
ClientIPFromContext retrieves the client IP address from the context.
func ClientIPPrincipalFunc ¶ added in v0.54.0
ClientIPPrincipalFunc is a default PrincipalFunc that extracts the client's IP address from the request for rate limiting purposes.
GetClientIP trusts the X-Forwarded-For, Forwarded, and X-Real-IP headers unconditionally (see its doc comment). Used as the default principal here, that means a client not behind a trusted, header-stripping proxy can set any of those headers to a different value on every request and get a fresh rate-limit bucket each time, defeating the limiter entirely. Deploy this default only behind a proxy that strips or overwrites these headers before they reach this process; otherwise supply a PrincipalFunc that does not derive from client-supplied headers.
func ContextWithClientIP ¶ added in v0.54.0
ContextWithClientIP extracts the client IP address from the request and stores it in the context. It checks X-Forwarded-For and X-Real-IP headers first (for proxied requests), then falls back to RemoteAddr.
func CreateHTTPHeaderFromMap ¶
CreateHTTPHeaderFromMap creates a new http.Header from a map[string]string.
func GetClientIP ¶ added in v0.54.0
GetClientIP extracts the client IP address from a request. It checks X-Forwarded-For and X-Real-IP headers first (for proxied requests), then falls back to RemoteAddr.
It is suitable for display and logging only. For a rate-limit key, access control or any other trust decision use ClientIPResolver.ClientAddr, which ignores these headers unless the peer is a configured trusted proxy.
X-Forwarded-For, Forwarded, and X-Real-IP are ordinary request headers: any client can set them to an arbitrary value, and this function trusts them unconditionally with no allowlist of known proxy addresses. Unless the caller has independently verified that the request reached this process through a proxy it controls, which strips or overwrites these headers before forwarding, the returned value must be treated as attacker-controlled input -- not used as an identity or trust boundary for rate limiting, access control, or audit logging without that guarantee in place.
func MarshalHeader ¶ added in v0.52.0
func MarshalHeader(v any, opts HTTPMarshalOptions) (http.Header, error)
MarshalHeader encodes a struct into an http.Header using the provided options.
RFC 9110 Compliance: For slice fields ([]string), each element is added as a separate header occurrence using http.Header.Add(). This is compliant with RFC 9110 Section 5.5, which allows multiple header fieldSet lines with the same name. Values containing commas, quotes, or other special characters are preserved as-is in each occurrence.
Example:
type Example struct {
Values []string
}
ex := Example{Values: []string{"val1", "val2,with,comma"}}
// Produces:
// X-Values: val1
// X-Values: val2,with,comma
Example ¶
ExampleMarshalHeader demonstrates basic marshaling of a struct to headers.
package main
import (
"fmt"
dhttp "github.com/dioad/net/http"
)
func main() {
type UserInfo struct {
Name string `header:"X-User-Name"`
Roles []string `header:"X-User-Roles"`
ID int `header:"X-User-Id"`
}
user := UserInfo{
Name: "Jane Doe",
Roles: []string{"admin", "editor"},
ID: 12345,
}
// Use DefaultHTTPMarshalOptions which doesn't add any prefix, struct name or change case.
// Field names will be determined by the `header` tag if present,
header, err := dhttp.MarshalHeader(user, dhttp.DefaultHTTPMarshalOptions())
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("X-User-Name: %s\n", header.Get("X-User-Name"))
fmt.Printf("X-User-Roles: %v\n", header.Values("X-User-Roles"))
fmt.Printf("X-User-ID: %s\n", header.Get("X-User-Id"))
}
Output: X-User-Name: Jane Doe X-User-Roles: [admin editor] X-User-ID: 12345
Example (CustomTags) ¶
ExampleMarshalHeader_customTags demonstrates using custom header tags.
package main
import (
"fmt"
"log"
dhttp "github.com/dioad/net/http"
)
func main() {
type Metadata struct {
RequestID string `header:"Request-Id"`
TraceID string `header:"Trace-Id"`
Internal string `header:"-"` // This fieldSet will be ignored
}
metadata := Metadata{
RequestID: "req-789",
TraceID: "trace-abc",
Internal: "should-not-appear",
}
opts := dhttp.DefaultHTTPMarshalOptions()
headers, err := dhttp.MarshalHeader(metadata, opts)
if err != nil {
log.Fatal(err)
}
fmt.Println("Headers with custom tags:")
fmt.Printf(" request-id: %s\n", headers.Get("Request-Id"))
fmt.Printf(" trace-id: %s\n", headers.Get("Trace-Id"))
fmt.Printf(" internal present: %v\n", headers.Get("Internal") != "")
}
Output: Headers with custom tags: request-id: req-789 trace-id: trace-abc internal present: false
Example (Options) ¶
ExampleMarshalHeader_options demonstrates usage of HeaderMarshalOptions to customize header names.
package main
import (
"fmt"
dhttp "github.com/dioad/net/http"
)
func main() {
type AppConfig struct {
Enabled bool
Timeout int
}
cfg := AppConfig{
Enabled: true,
Timeout: 30,
}
// Using options to add a prefix and include struct name in header names.
// Field names are automatically converted to kebab-case.
opts := dhttp.HTTPMarshalOptions{
Prefix: "X-App",
IncludeStructName: true,
}
header, err := dhttp.MarshalHeader(cfg, opts)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Header names are generated as Prefix-StructName-FieldName (in kebab-case)
// and canonicalized by http.Header.
fmt.Printf("X-App-App-Config-Enabled: %s\n", header.Get("X-App-App-Config-Enabled"))
fmt.Printf("X-App-App-Config-Timeout: %s\n", header.Get("X-App-App-Config-Timeout"))
}
Output: X-App-App-Config-Enabled: true X-App-App-Config-Timeout: 30
Example (Rfc9110Compliance) ¶
ExampleMarshalHeader_rfc9110Compliance demonstrates RFC 9110 compliance for handling multiple header occurrences.
package main
import (
"fmt"
dhttp "github.com/dioad/net/http"
)
func main() {
type DataList struct {
Items []string
}
// Data with values containing commas
data := DataList{
Items: []string{"item1", "item2,with,comma", "item3"},
}
opts := dhttp.DefaultHTTPMarshalOptions()
// Marshal to headers
headers, _ := dhttp.MarshalHeader(data, opts)
// Show how multiple occurrences are created (RFC 9110 Section 5.5)
fmt.Println("Multiple header occurrences:")
for _, item := range headers.Values("Items") {
fmt.Printf(" items: %s\n", item)
}
// Unmarshal back - values are preserved exactly
var result DataList
_ = dhttp.UnmarshalHeader(headers, &result, opts)
fmt.Printf("\nUnmarshaled values:\n")
for i, item := range result.Items {
fmt.Printf(" [%d]: %s\n", i, item)
}
}
Output: Multiple header occurrences: items: item1 items: item2,with,comma items: item3 Unmarshaled values: [0]: item1 [1]: item2,with,comma [2]: item3
Example (WithoutStructName) ¶
ExampleMarshalHeader_withoutStructName demonstrates encoding without the struct name in headers.
package main
import (
"fmt"
"log"
dhttp "github.com/dioad/net/http"
)
func main() {
type Config struct {
APIKey string
Region string
}
config := Config{
APIKey: "secret-key",
Region: "us-west-2",
}
// Configure without struct name
opts := dhttp.HTTPMarshalOptions{
Prefix: "X",
IncludeStructName: false,
}
headers, err := dhttp.MarshalHeader(config, opts)
if err != nil {
log.Fatal(err)
}
fmt.Println("Headers without struct name:")
fmt.Printf(" X-ApiKey: %s\n", headers.Get("X-Apikey"))
fmt.Printf(" X-Region: %s\n", headers.Get("X-Region"))
}
Output: Headers without struct name: X-ApiKey: secret-key X-Region: us-west-2
func MarshalQuery ¶ added in v0.54.0
func MarshalQuery(v any, opts HTTPMarshalOptions) (string, error)
MarshalQuery encodes a struct into a URI query string using the provided options.
Example usage: type QueryParams struct { Search string `query:"search"` Tags []string `query:"tags"` } params := QueryParams{Search: "example", Tags: []string{"go", "http"}} queryString, err := MarshalQuery(params, opts).
func MergedHTTPHeader ¶ added in v0.67.3
MergedHTTPHeader returns a clone of baseHeaders with headerMap's entries set on top of it. baseHeaders itself is not mutated; use the returned http.Header.
func NewPersistentCookieStore ¶
func NewPersistentCookieStore(config CookieConfig) (*sessions.CookieStore, error)
NewPersistentCookieStore creates a persistent cookie store from the provided configuration.
func NewSessionCookieStore ¶
func NewSessionCookieStore(config CookieConfig) (*sessions.CookieStore, error)
NewSessionCookieStore creates a session cookie store from the provided configuration.
func NewUnixSocketClient ¶ added in v0.39.0
NewUnixSocketClient returns an *http.Client that dials the Unix domain socket at path for every request, ignoring the request's own network/address.
func RequestIDMiddleware ¶ added in v0.60.0
RequestIDMiddleware always generates a fresh UUID v4 for every request, sets it on the response as X-Request-ID, and enriches the context logger with request_id via UpdateContext so the field is visible to all code that reads zerolog.Ctx(r.Context()) — including deferred access-log callbacks that captured r before this middleware ran.
The request's own X-Request-ID header is intentionally ignored so that clients cannot influence the ID that appears in server logs.
Handlers retrieve the per-request logger with:
logger := zerolog.Ctx(r.Context())
func StandardLogger ¶ added in v0.36.1
StandardLogger creates a zerolog.Logger with standard fields for HTTP access logging. The "ip" field is resolved from X-Forwarded-For or X-Real-IP headers when present, falling back to RemoteAddr. Raw proxy headers and RemoteAddr are also included when set.
"resolved_client_ip" is only as trustworthy as GetClientIP's input: absent a trusted, header-stripping proxy in front of this process, any client can set it to an arbitrary value. It is logged alongside the raw "remote_addr" and proxy headers precisely so a reader can cross-check it rather than treat it as verified; do not use it alone as an audit trail of a request's true origin.
func UnmarshalHeader ¶ added in v0.52.0
func UnmarshalHeader(header http.Header, v any, opts HTTPMarshalOptions) error
UnmarshalHeader decodes an http.Header into a struct using the provided options.
RFC 9110 Compliance: Multiple header fieldSet occurrences with the same name are unmarshaled into slice fields ([]string) using http.Header.Values(). This retrieves all values for the header in the order they were added, preserving the semantics defined in RFC 9110 Section 5.5. Each value is kept as-is without parsing commas or other delimiters.
Example:
// Given headers:
// X-Values: val1
// X-Values: val2,with,comma
type Example struct {
Values []string
}
var ex Example
err := UnmarshalHeader(headers, &ex, opts)
Results in: ex.Values = []string{"val1", "val2,with,comma"}.
Example ¶
ExampleUnmarshalHeader demonstrates basic unmarshaling from headers to a struct.
package main
import (
"fmt"
"net/http"
dhttp "github.com/dioad/net/http"
)
func main() {
type UserInfo struct {
Name string `header:"X-User-Name"`
Roles []string `header:"X-User-Roles"`
ID int `header:"X-User-Id"`
}
header := http.Header{}
header.Set("X-User-Name", "John Doe")
header.Add("X-User-Roles", "viewer")
header.Add("X-User-Roles", "support")
header.Set("X-User-Id", "67890")
var user UserInfo
err := dhttp.UnmarshalHeader(header, &user, dhttp.DefaultHTTPMarshalOptions())
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Name: %s\n", user.Name)
fmt.Printf("Roles: %v\n", user.Roles)
fmt.Printf("ID: %d\n", user.ID)
}
Output: Name: John Doe Roles: [viewer support] ID: 67890
Example (Middleware) ¶
ExampleUnmarshalHeader_middleware demonstrates using header marshaling in HTTP middleware.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
dhttp "github.com/dioad/net/http"
)
func main() {
type RequestContext struct {
TenantID string
UserRole string
}
// Create a middleware that decodes headers into a struct
middleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
opts := dhttp.HTTPMarshalOptions{
Prefix: "X-Context",
IncludeStructName: false,
}
var ctx RequestContext
err := dhttp.UnmarshalHeader(r.Header, &ctx, opts)
if err != nil {
http.Error(w, "Invalid context headers", http.StatusBadRequest)
return
}
// Use the decoded context
fmt.Printf("Processing request for tenant: %s, role: %s\n", ctx.TenantID, ctx.UserRole)
next.ServeHTTP(w, r)
})
}
// Create a simple handler
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Wrap with middleware
wrappedHandler := middleware(handler)
// Simulate a request with headers
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/api/data", nil)
req.Header.Set("X-Context-Tenantid", "tenant-123")
req.Header.Set("X-Context-Userrole", "admin")
// Create a response recorder
w := httptest.NewRecorder()
// Process the request
wrappedHandler.ServeHTTP(w, req)
}
Output: Processing request for tenant: tenant-123, role: admin
func UnmarshalHeaderFromRequest ¶ added in v0.54.0
func UnmarshalHeaderFromRequest(req *http.Request, v any, opts HTTPMarshalOptions) error
UnmarshalHeaderFromRequest is a helper function that extracts headers from an http.Request and unmarshals them into a struct using the provided options.
func UnmarshalQuery ¶ added in v0.54.0
func UnmarshalQuery(rawQuery string, v any, opts HTTPMarshalOptions) error
UnmarshalQuery decodes a URI query string into a struct using the provided options. The rawQuery parameter should be the part of the URL after the '?' character, without the '?' itself. Example usage: type QueryParams struct { Search string `query:"search"` Tags []string `query:"tags"` } var params QueryParams err := UnmarshalQuery("search=example&tags=go&tags=http", ¶ms, opts)
Results in: params.Search = "example", params.Tags = []string{"go", "http"}.
func UnmarshalQueryFromRequest ¶ added in v0.54.0
func UnmarshalQueryFromRequest(req *http.Request, v any, opts HTTPMarshalOptions) error
UnmarshalQueryFromRequest unmarshals req's raw query string into v; see UnmarshalQuery.
func WithPrincipalFunc ¶ added in v0.54.0
func WithPrincipalFunc(getPrincipal PrincipalFunc) func(*RateLimiter)
WithPrincipalFunc allows configuring the function used to extract the principal from incoming HTTP requests.
func WithRateLimitLogger ¶ added in v0.54.0
func WithRateLimitLogger(logger zerolog.Logger) func(*RateLimiter)
WithRateLimitLogger allows configuring a logger for the rate limiter to log rate limit events and decisions.
func WithRateLimitSource ¶ added in v0.54.0
func WithRateLimitSource(source ratelimit.RateLimitSource) func(*RateLimiter)
WithRateLimitSource allows configuring a dynamic rate limit source that can provide rate limits based on the principal or other factors. Note: WithRateLimitSource and WithStaticRateLimit are mutually exclusive. If both are configured, the source takes precedence.
func WithRateLimiterRegistry ¶ added in v0.61.0
func WithRateLimiterRegistry(reg prometheus.Registerer) func(*RateLimiter)
WithRateLimiterRegistry sets the Prometheus registry used to register the rate-limit counter. When not set, prometheus.DefaultRegisterer is used.
func WithStaticRateLimit ¶ added in v0.54.0
func WithStaticRateLimit(requestsPerSecond float64, burst int) func(*RateLimiter)
WithStaticRateLimit allows configuring static rate limits with a specified number of requests per second and burst size. Note: WithStaticRateLimit and WithRateLimitSource are mutually exclusive. If both are configured, static limits are ignored.
Types ¶
type BodySizeLimiter ¶ added in v0.54.0
type BodySizeLimiter struct {
MaxBodyBytes int64
}
BodySizeLimiter is a middleware that limits the size of incoming request bodies.
func NewBodySizeLimiter ¶ added in v0.54.0
func NewBodySizeLimiter(opts ...BodySizeLimiterOpt) *BodySizeLimiter
NewBodySizeLimiter creates a new BodySizeLimiter with the provided options.
func (*BodySizeLimiter) Wrap ¶ added in v0.54.0
func (l *BodySizeLimiter) Wrap(next http.Handler) http.Handler
Wrap wraps an http.HandlerFunc to limit the request body size. Rejection events are logged using the request-scoped zerolog context logger so that request_id, principal, and other context fields are automatically included.
type BodySizeLimiterOpt ¶ added in v0.54.0
type BodySizeLimiterOpt func(*BodySizeLimiter)
BodySizeLimiterOpt defines a functional option for configuring the BodySizeLimiter.
func WithMaxBodyBytes ¶ added in v0.54.0
func WithMaxBodyBytes(maxBytesSize int64) BodySizeLimiterOpt
WithMaxBodyBytes sets the maximum allowed body size for requests. If not set, DefaultMaxBodyBytes is used.
type CORSConfig ¶ added in v0.76.0
type CORSConfig struct {
// AllowedOrigins are the origins that may call the API. "*" allows every
// origin.
AllowedOrigins []string `desc:"origins that may call the API" mapstructure:"allowed-origins"`
// AllowLocalhost also allows localhost origins. It is for a local UI that
// calls the API and for development. With AllowCredentials it lets any page
// on the user's machine make credentialed requests, so enable it only
// where that is meant.
AllowLocalhost bool `desc:"also allow localhost origins" mapstructure:"allow-localhost"`
// AllowedMethods defaults to the methods rs/cors allows, GET, POST and HEAD.
AllowedMethods []string `desc:"methods allowed on cross-origin requests" mapstructure:"allowed-methods"`
// AllowedHeaders defaults to Content-Type and Authorization.
AllowedHeaders []string `desc:"request headers allowed on cross-origin requests" mapstructure:"allowed-headers"`
// ExposedHeaders are the response headers a browser may read.
ExposedHeaders []string `desc:"response headers exposed to browsers" mapstructure:"exposed-headers"`
// AllowCredentials lets browsers send cookies and authorisation headers.
AllowCredentials bool `desc:"allow credentialed cross-origin requests" mapstructure:"allow-credentials"`
// AllowPrivateNetwork answers Private Network Access preflights, for a
// public page calling an API on a private network.
AllowPrivateNetwork bool `desc:"allow private network access preflights" mapstructure:"allow-private-network"`
// MaxAgeSeconds is how long browsers may cache a preflight response. It
// defaults to DefaultCORSMaxAge.
MaxAgeSeconds int `desc:"seconds a preflight response may be cached" mapstructure:"max-age-seconds"`
}
CORSConfig is the cross-origin policy of an API, in the form services take it in their configuration. Options turns it into rs/cors options and Middleware into a middleware.
Nothing is allowed unless an origin is listed or AllowLocalhost is set; an empty config is closed, unlike rs/cors, which allows every origin when it is given none.
func (CORSConfig) Middleware ¶ added in v0.76.0
func (c CORSConfig) Middleware(logger zerolog.Logger, debug bool) Middleware
Middleware returns the CORS middleware for c. See Options.
type Client ¶
type Client struct {
Config *ClientConfig
}
Client describes an HTTP client for making requests to a base URL.
func NewClient ¶
func NewClient(config *ClientConfig) (*Client, error)
NewClient creates a new HTTP client with the provided configuration. It returns an error if the configuration is missing required fields. BaseURL is optional; it is only required when calling ResolveRelativeRequestPath.
func NewDefaultClient ¶
func NewDefaultClient() *Client
NewDefaultClient creates a new HTTP client with default configuration.
type ClientConfig ¶
type ClientConfig struct {
BaseURL *url.URL
Client *http.Client
UserAgent string
RequestModifier func(*http.Request) error
}
ClientConfig describes the configuration for an HTTP client.
type ClientIPConfig ¶ added in v0.77.1
type ClientIPConfig struct {
// TrustedProxies are the ranges of the proxies in front of the service,
// in CIDR notation. Forwarding headers are honoured only from a peer in
// one of them.
TrustedProxies []string `desc:"CIDR ranges of proxies whose forwarding headers are trusted" mapstructure:"trusted-proxies"`
// TrustedHeader names a header set by an edge that this process can only
// be reached through, such as Fly-Client-IP on fly.io. It takes
// precedence over TrustedProxies.
TrustedHeader string `desc:"header set by the edge proxy that is trusted verbatim" mapstructure:"trusted-header"`
}
ClientIPConfig is the trust model of ClientIPResolver, in the form services take it in their configuration. An empty config trusts no header, so the client address is the connection's address.
func (ClientIPConfig) Check ¶ added in v0.77.1
func (c ClientIPConfig) Check(findings *configcheck.Collector)
Check reports to c a trusted proxy that is not a CIDR range, and trust modes set together. c is positioned at the config's own block.
func (ClientIPConfig) Resolver ¶ added in v0.77.1
func (c ClientIPConfig) Resolver() (*ClientIPResolver, error)
Resolver returns the ClientIPResolver for c. It returns an error for a trusted proxy that is not a CIDR range; Check reports the same.
type ClientIPResolver ¶ added in v0.67.3
type ClientIPResolver struct {
// contains filtered or unexported fields
}
ClientIPResolver resolves a request's client address under an explicit trust model, unlike the package-level GetClientIP, which trusts forwarding headers unconditionally (see its doc comment). Zero or one trust mode may be configured:
- WithTrustedHeader trusts one named header verbatim, for platforms whose edge sets a header this process can only receive by going through that edge (e.g. fly.io's Fly-Client-IP -- see NewFlyClientIPResolver).
- WithTrustedProxyCIDRs walks X-Forwarded-For, or failing that Forwarded, from the right against a caller-supplied set of trusted proxy ranges, for platforms that publish stable ranges (AWS ALB, Azure Application Gateway, Cloudflare, self-hosted nginx, etc).
If both are configured, WithTrustedHeader takes precedence. If neither is configured, ClientAddr is the request's direct peer address (RemoteAddr) only -- it never trusts a client-supplied header, unlike GetClientIP.
When the listener understands the PROXY protocol (see WithProxyProtocol), RemoteAddr is already the real client, so the zero-configuration resolver is the right choice behind such a proxy.
func NewClientIPResolver ¶ added in v0.67.3
func NewClientIPResolver(opts ...ClientIPResolverOption) *ClientIPResolver
NewClientIPResolver creates a ClientIPResolver with the given options.
func NewFlyClientIPResolver ¶ added in v0.67.3
func NewFlyClientIPResolver() *ClientIPResolver
NewFlyClientIPResolver returns a ClientIPResolver configured to trust Fly Proxy's Fly-Client-IP header, which reflects Fly Proxy's own direct observation of the TCP peer it accepted a connection from -- not a value copied from client input, so there is nothing for a client to spoof. This is correct as long as this process is only reachable by going through fly-proxy (the normal fly.io deployment shape; Fly Machines aren't directly Internet-routable otherwise). If another CDN or proxy is placed in front of fly.io, Fly-Client-IP reflects that intermediate hop instead of the true client -- use WithTrustedProxyCIDRs with that layer's published ranges instead.
func (*ClientIPResolver) ClientAddr ¶ added in v0.77.1
func (c *ClientIPResolver) ClientAddr(r *http.Request) netip.Addr
ClientAddr resolves r's client address under the configured trust mode. It returns the zero Addr when neither the headers nor RemoteAddr yield a valid address. IPv4-mapped IPv6 addresses are returned as IPv4 and zones are dropped, so the result is a stable key.
func (*ClientIPResolver) ClientIP
deprecated
added in
v0.67.3
func (c *ClientIPResolver) ClientIP(r *http.Request) string
ClientIP resolves r's client address as a string, falling back to the raw RemoteAddr when it cannot be parsed.
Deprecated: Use ClientAddr, which returns a netip.Addr.
func (*ClientIPResolver) PrincipalFunc ¶ added in v0.67.3
func (c *ClientIPResolver) PrincipalFunc(r *http.Request) (string, error)
PrincipalFunc adapts ClientAddr to the PrincipalFunc signature, for use with WithRateLimiterPrincipalFunc/WithPrincipalFunc.
type ClientIPResolverOption ¶ added in v0.67.3
type ClientIPResolverOption func(*ClientIPResolver)
ClientIPResolverOption configures a ClientIPResolver.
func WithTrustedHeader ¶ added in v0.67.3
func WithTrustedHeader(name string) ClientIPResolverOption
WithTrustedHeader configures the resolver to trust one named header verbatim. Use this only when the deployment topology guarantees this process receives no traffic that hasn't passed through the edge that sets this header -- there is no source-address check involved.
func WithTrustedProxyCIDRs ¶ added in v0.67.3
func WithTrustedProxyCIDRs(cidrs ...netip.Prefix) ClientIPResolverOption
WithTrustedProxyCIDRs configures the resolver to walk X-Forwarded-For (or Forwarded, when that is absent) from the right, skipping entries whose address falls within the given CIDR ranges, and returning the first entry that doesn't -- the RFC 7239-style trusted-proxy-list algorithm. The request's direct peer (RemoteAddr) must also fall within the trusted set for the headers to be consulted at all; otherwise the peer is untrusted and is used directly, since any header it presents is unverified.
An entry that cannot be parsed ends the walk: it was written by a hop this process cannot vouch for, so the nearest address before it is returned.
type Config ¶
type Config struct {
// TLSConfig is the TLS configuration for the server
TLSConfig *tls.Config
// ListenAddress is the address to listen on, e.g. ":8080"
ListenAddress string
// ReadHeaderTimeout is the maximum duration for reading request headers.
// If zero, defaults to defaultReadHeaderTimeout.
// Setting this prevents ghost TCP connections (accepted but no HTTP request sent)
// from blocking graceful shutdown for up to 5 seconds.
ReadHeaderTimeout time.Duration
// IdleTimeout is the maximum duration an idle (keep-alive) connection will
// remain open before being closed. If zero, Go's http.Server defaults to
// ReadTimeout.
IdleTimeout time.Duration
// EnablePrometheusMetrics enables the /metrics endpoint for Prometheus metrics
//
// Deprecated: Use the WithPrometheusMetrics option. The field will be
// removed in the next major version.
EnablePrometheusMetrics bool
// EnableDebug enables the /debug endpoint for pprof debugging
//
// Deprecated: Use the WithDebug option. The field will be removed in the
// next major version.
EnableDebug bool
// EnableStatus enables the /status endpoint for server status
//
// Deprecated: Use the WithStatus option. The field will be removed in the
// next major version.
EnableStatus bool
// EnableProxyProtocol enables the PROXY protocol for client IP forwarding
//
// Deprecated: Use the WithProxyProtocol option. The field will be removed
// in the next major version.
EnableProxyProtocol bool
// ProxyProtocolPolicy says what happens to a connection without a PROXY
// header when EnableProxyProtocol is set. Empty means
// ProxyProtocolRequire.
//
// Deprecated: Pass the policy to the WithProxyProtocol option. The field
// will be removed in the next major version.
ProxyProtocolPolicy ProxyProtocolPolicy
// EnableHealth enables the /health/live and /health/ready endpoints for health checks
//
// Deprecated: Use the WithHealth option. The field will be removed in the
// next major version.
EnableHealth bool
}
Config represents the configuration for an HTTP server.
type CookieConfig ¶
type CookieConfig struct {
// KeyPairs is ordered newest-first: the first pair signs/encrypts new
// cookies, and every pair is tried when decoding, so old pairs can be
// kept around during a rotation window and then dropped once no
// outstanding cookie could still be using them. At least one pair is
// required.
KeyPairs []CookieKeyPair `mapstructure:"key-pairs"`
MaxAge int `mapstructure:"max-age"`
Domain string `mapstructure:"domain"`
}
CookieConfig describes the configuration for HTTP cookies.
type CookieKeyPair ¶ added in v0.67.3
type CookieKeyPair struct {
Base64AuthenticationKey string `mapstructure:"base64-authentication-key"`
// Base64EncryptionKey is optional. Unset, cookie contents are signed
// but not encrypted, which keeps them inspectable for local debugging.
// When set, it must decode to 16, 24, or 32 bytes to select AES-128,
// AES-192, or AES-256.
Base64EncryptionKey string `mapstructure:"base64-encryption-key"`
}
CookieKeyPair is one (authentication, encryption) key pair used to sign and, optionally, encrypt session cookies.
type EnforceTLSHandler ¶ added in v0.37.0
type EnforceTLSHandler struct {
// contains filtered or unexported fields
}
EnforceTLSHandler wraps an HTTP handler to enforce TLS connections.
func NewEnforceTLSHandler ¶ added in v0.61.0
func NewEnforceTLSHandler(enforce bool) *EnforceTLSHandler
NewEnforceTLSHandler creates an EnforceTLSHandler that rejects non-TLS requests when enforce is true.
type HTTPMarshalOptions ¶ added in v0.54.0
type HTTPMarshalOptions struct {
// Prefix is prepended to all parameter names (e.g., "X" results in "X-Field-Name")
Prefix string
// IncludeStructName includes the struct type name in the parameter (e.g., "X-Example-Field-Name")
IncludeStructName bool
// DefaultKebabCase converts fieldSet names to kebab-case by default (e.g., "FieldName" becomes "field-name")
DefaultKebabCase bool
}
HTTPMarshalOptions configures how struct fields are marshaled to/from HTTP headers or query parameters.
func DefaultHTTPMarshalOptions ¶ added in v0.54.0
func DefaultHTTPMarshalOptions() HTTPMarshalOptions
DefaultHTTPMarshalOptions returns default options with no prefix and no struct name.
type HandlerWrapper ¶
HandlerWrapper is a function type that wraps an HTTP handler.
func DefaultCombinedLogHandler ¶
func DefaultCombinedLogHandler(logWriter io.Writer) HandlerWrapper
DefaultCombinedLogHandler returns a HandlerWrapper that logs HTTP requests using the combined log format. It wraps the handler with ProxyHeaders middleware so that X-Forwarded-For and X-Real-IP headers are reflected in the logged client IP.
func ZerologStructuredLogHandler ¶
func ZerologStructuredLogHandler(logger zerolog.Logger) HandlerWrapper
ZerologStructuredLogHandler returns a HandlerWrapper that uses zerolog for structured logging.
func ZerologStructuredLogHandlerWithFormatter ¶ added in v0.36.1
func ZerologStructuredLogHandlerWithFormatter(logger zerolog.Logger, formatter StructuredLoggerFormatter) HandlerWrapper
ZerologStructuredLogHandlerWithFormatter returns a HandlerWrapper that uses a custom formatter for structured logging.
type HealthRegistry ¶ added in v0.55.0
type HealthRegistry struct {
// contains filtered or unexported fields
}
HealthRegistry manages the collection and aggregation of resource health and status. It is safe for concurrent use, so servers sharing one (see NewOperationalServer) can register sources while either is serving.
func NewHealthRegistry ¶ added in v0.55.0
func NewHealthRegistry(logger zerolog.Logger) *HealthRegistry
NewHealthRegistry creates a new HealthRegistry.
func (*HealthRegistry) AddStaticMetadata ¶ added in v0.55.0
func (h *HealthRegistry) AddStaticMetadata(key string, value any)
AddStaticMetadata adds static metadata to be included in status responses.
func (*HealthRegistry) Register ¶ added in v0.55.0
func (h *HealthRegistry) Register(path string, r Resource)
Register adds a resource to the health registry at the given path. Server's AddResource calls it for every resource it mounts; the resource's Live, Ready and Status, where it implements them, are aggregated by /health/live, /health/ready and /status.
func (*HealthRegistry) RegisterHealthSource ¶ added in v0.71.2
func (h *HealthRegistry) RegisterHealthSource(name string, source any) error
RegisterHealthSource adds source to the /health/live, /health/ready and /status aggregates under name, without mounting any route. source must implement at least one of LivenessResource, ReadinessResource and StatusResource; unlike Register it needs no Handler. Use it for a health check that has nothing to serve itself, such as a service's readiness gate. name shares a namespace with the paths of registered resources, and registering the same name again replaces the earlier source.
type Instrument ¶ added in v0.61.0
Instrument wraps an http.Handler with telemetry instrumentation.
type LivenessResource ¶ added in v0.54.0
LivenessResource is an interface for resources that can report their liveness.
type LogLevelSetter ¶ added in v0.48.0
type LogLevelSetter interface {
// SetLogLevel sets the global log level for zerolog.
SetLogLevel(level string) error
// SetLogLevelWithDuration sets the global log level for zerolog and returns the time when it expires.
SetLogLevelWithDuration(level string, duration time.Duration) (time.Time, error)
// OriginalLogLevel returns the original log level before any changes.
OriginalLogLevel() string
// CurrentLogLevel returns the current log level.
CurrentLogLevel() string
// ResetLogLevel resets the log level to the original level.
ResetLogLevel()
// ExpiresAt returns the time when the current log level will expire.
ExpiresAt() time.Time
}
LogLevelSetter defines an interface for setting and managing log levels.
func NewZeroLogLevelSetter ¶ added in v0.48.0
func NewZeroLogLevelSetter() LogLevelSetter
NewZeroLogLevelSetter creates a new LogLevelSetter for zerolog.
type MetadataResource ¶ added in v0.72.0
type MetadataResource struct {
// Version is the release version, such as "v1.2.3".
Version string
// Commit is the source revision the binary was built from.
Commit string
// Date is the build or commit time.
Date string
}
MetadataResource serves a server's build metadata: its version, commit and build date. Every Dioad server exposes the same document, so they share this resource rather than each carrying a copy.
Example ¶
resource := NewMetadataResource("v1.2.3", "abc123", "2026-11-14")
rec := httptest.NewRecorder()
resource.Handler().ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil))
var body map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
fmt.Println("decode:", err)
return
}
fmt.Println(rec.Code, body["version"], body["commit"], body["date"])
Output: 200 v1.2.3 abc123 2026-11-14
func NewMetadataResource ¶ added in v0.72.0
func NewMetadataResource(version, commit, date string) *MetadataResource
NewMetadataResource returns a MetadataResource for the given build values, normally set by the binary's ldflags. A value left empty is filled from the build information Go embeds in the binary (the main module's version, and the vcs.revision and vcs.time settings), so a binary built without ldflags still reports what it can.
func (*MetadataResource) Get ¶ added in v0.72.0
func (r *MetadataResource) Get() http.HandlerFunc
Get returns a handler that responds with the version, commit and date.
func (*MetadataResource) Handler ¶ added in v0.72.0
func (r *MetadataResource) Handler() http.Handler
Handler returns the HTTP handler for the resource: GET and OPTIONS at its root, with or without a trailing slash.
func (*MetadataResource) Options ¶ added in v0.72.0
func (r *MetadataResource) Options() http.HandlerFunc
Options returns a handler for OPTIONS requests, which says what the resource allows.
type MetricSet ¶
type MetricSet struct {
RequestCounter *prometheus.CounterVec
RequestDuration *prometheus.HistogramVec
RequestSize *prometheus.HistogramVec
ResponseSize *prometheus.HistogramVec
InFlightGauge prometheus.Gauge
// contains filtered or unexported fields
}
MetricSet holds the standard HTTP server instrumentation metrics.
func NewMetricSet ¶
func NewMetricSet(r *prometheus.Registry) *MetricSet
NewMetricSet creates a new MetricSet and immediately registers its metrics with the provided registry.
func (*MetricSet) Middleware ¶
Middleware instruments the handler with prometheus metrics. It uses the provided ServeMux to derive the matched route pattern for the "route" label, preventing high-cardinality Prometheus series that would result from using raw URL paths.
func (*MetricSet) Register ¶
func (m *MetricSet) Register(r prometheus.Registerer)
Register registers the metrics in the metric set with the given registerer.
type Middleware ¶ added in v0.55.0
Middleware is a standard function signature for HTTP middleware.
func CORSHandler ¶ added in v0.50.4
func CORSHandler(options cors.Options) Middleware
CORSHandler returns a middleware that handles Cross-Origin Resource Sharing (CORS).
type OperationalConfig ¶ added in v0.71.1
type OperationalConfig struct {
// ListenAddress is the address to listen on, e.g. ":8125".
ListenAddress string
// EnablePrometheusMetrics serves /metrics.
EnablePrometheusMetrics bool
// EnableStatus serves /status.
EnableStatus bool
// EnableDebug serves /debug (pprof). It exposes memory contents, so keep
// it off unless debugging.
EnableDebug bool
// TLSConfig, when set, serves the operational endpoints over TLS, for
// example with client-certificate verification where the listener is
// reachable beyond the platform.
TLSConfig *tls.Config
// EnableProxyProtocol accepts a PROXY protocol header, for a listener a
// proxy forwards to. Leave it off for a platform check or scraper that
// connects directly: with the default ProxyProtocolPolicy (require) a
// connection without a header is refused.
EnableProxyProtocol bool
// ProxyProtocolPolicy applies when EnableProxyProtocol is set; see
// WithProxyProtocol.
ProxyProtocolPolicy ProxyProtocolPolicy
}
OperationalConfig configures an operational server built by NewOperationalServer.
type OperationsConfig ¶ added in v0.73.0
type OperationsConfig struct {
// ManagementListenAddress is the host:port of the management listener that
// serves health, /metrics and, with enable-debug, pprof. Empty disables it.
ManagementListenAddress string `desc:"address of the management listener (health, metrics); empty disables it" mapstructure:"management-listen-address"`
// ManagementAllowNonLoopback confirms that the management listener may bind
// beyond loopback with nothing in front of it to authenticate callers. Check
// accepts a non-loopback address without it only when ManagementTLSServer
// requires client certificates.
ManagementAllowNonLoopback bool `` /* 197-byte string literal not displayed */
// ManagementEnableProxyProtocol accepts a PROXY protocol header on the
// management listener, for one a proxy forwards to. Leave it off for a
// platform check or scraper that connects directly.
ManagementEnableProxyProtocol bool `desc:"accept a PROXY protocol header on the management listener" mapstructure:"management-enable-proxy-protocol"`
// ManagementTLSServer serves the management listener over TLS. With
// client-auth-type RequireAndVerifyClientCert and a client-ca-file it also
// authenticates callers, which lets the listener bind beyond loopback
// without the acknowledgement. Convert it with tls.NewServerTLSConfig and
// set the result as OperationalConfig.TLSConfig.
ManagementTLSServer dtls.ServerConfig `desc:"TLS settings of the management listener" mapstructure:"management-tls-server"`
// EnablePrometheusMetrics serves /metrics on the management listener. Unset
// means on: the listener exists for health and metrics, and a service has to
// set it false to turn them off.
EnablePrometheusMetrics *bool `desc:"serve Prometheus metrics on the management listener (default true)" mapstructure:"enable-prometheus-metrics"`
// EnableDebug should only be true in development environments. Set to false
// in production to avoid exposing sensitive information.
EnableDebug bool `desc:"expose pprof and verbose diagnostics; development only" mapstructure:"enable-debug"`
// ShutdownDrainDelay is how long shutdown waits, after /health/ready starts
// reporting not-ready and before listeners close, so a load balancer stops
// routing new requests first. Set it to at least one probe interval. Zero
// (the default) closes listeners immediately.
ShutdownDrainDelay time.Duration `desc:"how long shutdown waits after readiness fails before closing listeners" mapstructure:"shutdown-drain-delay"`
}
OperationsConfig holds the operational settings a dioad service takes under the same keys: the management listener, pprof, and the shutdown drain. A service embeds it squashed, so the keys sit at the top level of its YAML and its flags. Check validates it, and Operational maps it onto OperationalConfig.
func (OperationsConfig) Check ¶ added in v0.73.0
func (o OperationsConfig) Check(c *configcheck.Collector)
Check reports to c a management listener that is malformed or, without the acknowledgement, not loopback and not protected by client certificates, an acknowledgement given with no listener to apply to, a TLS block that does not check out, and a negative drain delay. The management listener serves health, /metrics and, with enable-debug, pprof, with no authentication of its own, so binding it beyond loopback has to be a deliberate choice. c is positioned at the service's configuration root.
func (OperationsConfig) Operational ¶ added in v0.73.0
func (o OperationsConfig) Operational() OperationalConfig
Operational returns the OperationalConfig for the management listener: health, /metrics unless turned off, and /debug when EnableDebug is set. Pass WithReadiness to NewOperationalServer so /health/ready reports the service's readiness, and set TLSConfig on the result from ManagementTLSServer and EnableStatus where the service has a status resource.
type PrincipalFunc ¶ added in v0.54.0
PrincipalFunc defines a function type that extracts a principal identifier from an HTTP request for rate limiting purposes.
func StaticPrincipalFunc ¶ added in v0.54.0
func StaticPrincipalFunc(principal string) PrincipalFunc
StaticPrincipalFunc returns a PrincipalFunc that always returns the given principal.
type ProxyProtocolPolicy ¶ added in v0.71.0
type ProxyProtocolPolicy string
ProxyProtocolPolicy is what a PROXY protocol listener does with a connection that does not start with a PROXY header. It is set explicitly here rather than left to go-proxyproto's DefaultPolicy, which changed from optional to required in v0.15.0 and silently changed what every listener accepted.
const ( // ProxyProtocolRequire refuses a connection without a PROXY header. Use it // when every client arrives through a proxy that adds one: a client that // reaches the port directly cannot then forge its source address. This is // the default. ProxyProtocolRequire ProxyProtocolPolicy = "require" // ProxyProtocolOptional uses a PROXY header when one is sent and accepts // a connection without one, for a listener reached both through a proxy // and directly (a platform health check, a metrics scrape). Anyone who // can reach the port directly can then send a header and choose the // source address the server sees. ProxyProtocolOptional ProxyProtocolPolicy = "optional" )
type RateLimiter ¶ added in v0.53.0
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides per-principal rate limiting for HTTP requests.
func NewRateLimiter ¶ added in v0.53.0
func NewRateLimiter(opts ...RateLimiterOption) *RateLimiter
NewRateLimiter creates a new rate limiter with static limits. requestsPerSecond: allowed requests per second per principal burst: maximum burst size
A PrincipalFunc must be configured via WithPrincipalFunc; there is no default, because the previous default (ClientIPPrincipalFunc) trusts client-supplied headers unconditionally and is unsafe unless the deployment is known to sit behind a trusted, header-stripping proxy -- see GetClientIP's doc comment and ClientIPResolver for safe alternatives. NewRateLimiter panics if no PrincipalFunc ends up configured.
func (*RateLimiter) Middleware ¶ added in v0.53.0
func (rl *RateLimiter) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware for rate limiting.
func (*RateLimiter) Stop ¶ added in v0.61.0
func (rl *RateLimiter) Stop()
Stop shuts down the background cleanup goroutine started by the rate limiter. It should be called when the RateLimiter is no longer needed to avoid a goroutine leak. Stop is safe to call multiple times.
type RateLimiterOption ¶ added in v0.54.0
type RateLimiterOption func(*RateLimiter)
RateLimiterOption is a functional option for configuring an HTTP RateLimiter.
type ReadinessResource ¶ added in v0.54.0
ReadinessResource is an interface for resources that can report their readiness.
type Resource ¶
Resource is a marker interface for HTTP resources. It mandates that a resource must provide an http.Handler that can be mounted onto the server's main multiplexer.
type RootResource ¶
type RootResource interface {
// Index Resource
Index() http.HandlerFunc
}
RootResource is an interface for the root resource of the server.
type Server ¶
type Server struct {
// Config is the server configuration
Config Config
// Logger is the logger for the server
Logger zerolog.Logger
// ResourceMap maps path prefixes to resources
ResourceMap map[string]Resource
// ListenAddr is the address the server is listening on. It is set once
// Start has returned, or once Serve has been called.
ListenAddr net.Addr
// LogHandler is the handler wrapper for logging requests
LogHandler HandlerWrapper
// HealthRegistry aggregates internal server health endpoints and metadata
HealthRegistry *HealthRegistry
// contains filtered or unexported fields
}
Server represents an HTTP server with various features like metrics, authentication, and resources.
func NewOperationalServer ¶ added in v0.71.1
func NewOperationalServer(primary *Server, cfg OperationalConfig, opts ...ServerOption) *Server
NewOperationalServer returns a server that serves primary's operational endpoints on a listener of their own: /health/live and /health/ready always, and /metrics, /status and /debug as cfg says.
It is for a platform health check and metrics scraper that cannot present credentials, while primary keeps authenticating its own routes. It shares primary's health registry, so a resource added to primary at any point is reported here, and its /metrics serves primary's request metrics with the process-wide default registry. It inherits none of primary's middlewares, authentication or resources, and none of its TLS or PROXY protocol settings: it serves plain HTTP with no PROXY protocol unless cfg says otherwise. Bind it where only the platform can reach it, or give it TLS with client verification.
opts are applied last, so WithLogger or WithMetricsGatherers can override the defaults. Pass WithReadiness to make /health/ready report a service's own readiness gate.
Example ¶
An operational server puts the primary server's health endpoints on a listener of their own, for a platform health check that cannot present the credentials the primary asks for. A health source added to the primary is reported there.
package main
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"sync/atomic"
"github.com/rs/zerolog"
dhttp "github.com/dioad/net/http"
)
// startGate is a health source that reports not ready until it is opened.
type startGate struct{ open atomic.Bool }
func (g *startGate) Ready(context.Context) (any, error) {
if !g.open.Load() {
return nil, errors.New("starting")
}
return "started", nil
}
// get returns the status, the X-Served-By header and the body of a GET.
func get(ctx context.Context, url string) (int, string, string) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, "", err.Error()
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, "", err.Error()
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
return resp.StatusCode, resp.Header.Get("X-Served-By"), string(body)
}
func main() {
ctx := context.Background()
primary := dhttp.NewServer(dhttp.Config{ListenAddress: "127.0.0.1:0"}, dhttp.WithLogger(zerolog.Nop()))
gate := &startGate{}
if err := primary.AddHealthSource("startup", gate); err != nil {
fmt.Println("health source:", err)
return
}
management := dhttp.NewOperationalServer(
primary,
dhttp.OperationalConfig{ListenAddress: "127.0.0.1:0"},
dhttp.WithLogger(zerolog.Nop()),
)
if err := management.Start(ctx); err != nil {
fmt.Println("start:", err)
return
}
ready := "http://" + management.ListenAddr.String() + "/health/ready"
status, _, _ := get(ctx, ready)
fmt.Println("before the gate opens:", status)
gate.open.Store(true)
status, _, _ = get(ctx, ready)
fmt.Println("after the gate opens:", status)
fmt.Println("shutdown:", management.Shutdown(ctx))
}
Output: before the gate opens: 503 after the gate opens: 200 shutdown: <nil>
func NewServer ¶
func NewServer(config Config, opts ...ServerOption) *Server
NewServer creates a new HTTP server with the given configuration and options Options can be used to customize the server, such as adding a logger, authentication, or metrics.
The operational endpoints are off unless an option turns them on: see WithHealth, WithStatus, WithPrometheusMetrics and WithDebug.
Example ¶
A server with a resource mounted under a path prefix and a middleware that runs for every request. Start returns once the listener is bound, and Shutdown waits for the serve loop to end.
package main
import (
"context"
"fmt"
"html"
"io"
"net/http"
"github.com/rs/zerolog"
dhttp "github.com/dioad/net/http"
)
// greetings is a Resource: a set of routes that a server mounts under one
// path prefix.
type greetings struct{}
func (greetings) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /{name}", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "hello, "+html.EscapeString(r.PathValue("name")))
})
return mux
}
// servedBy is a middleware that labels every response.
func servedBy(name string) dhttp.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Served-By", name)
next.ServeHTTP(w, r)
})
}
}
// get returns the status, the X-Served-By header and the body of a GET.
func get(ctx context.Context, url string) (int, string, string) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, "", err.Error()
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, "", err.Error()
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
return resp.StatusCode, resp.Header.Get("X-Served-By"), string(body)
}
func main() {
ctx := context.Background()
server := dhttp.NewServer(
dhttp.Config{ListenAddress: "127.0.0.1:0"},
dhttp.WithLogger(zerolog.Nop()),
dhttp.WithHealth(),
)
server.Use(servedBy("example"))
server.AddResource("/greetings", greetings{})
if err := server.Start(ctx); err != nil {
fmt.Println("start:", err)
return
}
base := "http://" + server.ListenAddr.String()
fmt.Println(get(ctx, base+"/greetings/world"))
status, _, _ := get(ctx, base+"/health/ready")
fmt.Println("ready:", status)
fmt.Println("shutdown:", server.Shutdown(ctx))
}
Output: 200 example hello, world ready: 200 shutdown: <nil>
func (*Server) AddHandler ¶
AddHandler adds a handler for the specified path.
func (*Server) AddHandlerFunc ¶
func (s *Server) AddHandlerFunc(path string, handler http.HandlerFunc)
AddHandlerFunc adds a handler function for the specified path.
func (*Server) AddHealthSource ¶ added in v0.71.2
AddHealthSource adds source to the server's /health/live, /health/ready and /status aggregates under name, without mounting a route. See HealthRegistry.RegisterHealthSource. A source added to a server is also reported by any operational server built from it.
func (*Server) AddResource ¶
func (s *Server) AddResource(pathPrefix string, r Resource, middlewares ...Middleware)
AddResource adds a resource to the server at the specified path prefix Optional middlewares can be provided to be applied exclusively to the resource's routes.
func (*Server) AddRootResource ¶
func (s *Server) AddRootResource(r RootResource)
AddRootResource sets the root resource for the server and registers its "/" route. The root resource's Index method will be called for any path that doesn't match other routes.
Safe to call at any point before the server starts actually accepting requests, regardless of whether some other method has already triggered initialiseServer (RegisterOnShutdown and Shutdown do, besides Serve/ListenAndServe): rootRouteOnce ensures "/" is registered exactly once, whichever of AddRootResource or initialiseServer runs first, rather than only ever inside initialiseServer's own one-time setup - a caller that finishes configuring the server (mounting resources, then calling AddRootResource) after something else already triggered initialisation would otherwise have "/" silently, permanently unregistered. "/" is never registered at all for servers that never call AddRootResource, so this doesn't affect callers that register their own catch-all pattern (e.g. "/{path...}") directly - registering "/" unconditionally would panic via net/http.ServeMux's duplicate-pattern check against such a caller.
func (*Server) AddStatusStaticMetadataItem ¶
AddStatusStaticMetadataItem adds a static metadata item to the status endpoint These items will be included in the "Metadata" section of the status response.
func (*Server) ConfigureTelemetryInstrument ¶
func (s *Server) ConfigureTelemetryInstrument(i Instrument)
ConfigureTelemetryInstrument configures the server with the given telemetry instrument.
func (*Server) Failed ¶ added in v0.72.0
Failed returns a channel that receives, at most once, the error that ended the serve loop started by Start other than by Shutdown or by closing the listener. It never receives for a server that was not started with Start.
func (*Server) ListenAndServe ¶
ListenAndServe starts the server with the TLS configuration from the server's config It creates a listener on the configured address and calls Serve.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS starts the server with the provided TLS configuration The tlsConfig will override any prior configuration in s.Config It creates a listener on the configured address and calls Serve.
func (*Server) Live ¶ added in v0.72.0
Live returns nil while the serve loop started by Start is running, and for a server that has not been started or that Shutdown stopped. It returns the error that ended the serve loop if that was unexpected.
func (*Server) MetricSet ¶ added in v0.60.0
MetricSet returns the server's HTTP instrumentation metric set.
func (*Server) RegisterOnShutdown ¶
func (s *Server) RegisterOnShutdown(f func())
RegisterOnShutdown registers a function to be called when the server is shutting down This function will be called in a new goroutine when Shutdown is called.
func (*Server) Serve ¶
Serve starts the server with the provided listener It initializes the server if needed, configures TLS and proxy protocol if enabled, and starts serving HTTP or HTTPS requests.
func (*Server) ServeTLS ¶
ServeTLS is a convenience method that calls Serve It's provided for compatibility with the http.Server interface.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server without interrupting any active connections It waits for all connections to finish or for the context to be canceled.
If the server was started with Start, Shutdown also waits for the serve loop to return, and reports the error that ended it unless that error is the one Shutdown itself causes.
func (*Server) Start ¶ added in v0.72.0
Start binds the address in Config.ListenAddress and serves on it in a goroutine, using the TLS configuration in Config.TLSConfig, if any. It returns once the listener is bound, so a bind failure (port in use, bad address) is returned to the caller instead of being logged from a goroutine after the caller has moved on. ListenAddr then holds the bound address, which is how to learn the port when ListenAddress asks for port 0.
After Start, Failed reports a serve loop that ends unexpectedly, Live reports whether it is still running, and Shutdown waits for it to return. A Server can be started once.
Example ¶
server := NewServer(Config{ListenAddress: "127.0.0.1:0"}, WithLogger(zerolog.Nop()))
if err := server.Start(context.Background()); err != nil {
fmt.Println("start:", err)
return
}
fmt.Println("live:", server.Live(context.Background()))
fmt.Println("shutdown:", server.Shutdown(context.Background()))
Output: live: <nil> shutdown: <nil>
func (*Server) Use ¶ added in v0.43.0
func (s *Server) Use(middlewares ...Middleware)
Use adds middleware to the server's global middleware chain. Any nil middlewares will be filtered out. Middlewares are executed in the order added.
type ServerOption ¶ added in v0.43.0
type ServerOption func(*Server)
ServerOption is a function that configures a Server.
func WithCORS ¶ added in v0.50.3
func WithCORS(options cors.Options) ServerOption
WithCORS returns a ServerOption that configures the server with the given CORS options.
func WithComponent ¶ added in v0.72.0
func WithComponent(name string) ServerOption
WithComponent returns a ServerOption that adds a "component" field to every log event the server emits: its own lifecycle and error events, its request log, and its health registry's. It tells servers apart when several run in one process, such as a control server and a management server. It applies whether it is given before or after WithLogger, and a logger that already carries a component is replaced by name.
func WithDebug ¶ added in v0.72.0
func WithDebug() ServerOption
WithDebug returns a ServerOption that serves pprof under /debug. pprof exposes memory contents, so keep it off a listener that untrusted clients can reach.
func WithHealth ¶ added in v0.72.0
func WithHealth() ServerOption
WithHealth returns a ServerOption that serves /health/live and /health/ready, aggregated from the server's resources and health sources.
func WithLogWriter ¶ added in v0.43.0
func WithLogWriter(w io.Writer) ServerOption
WithLogWriter returns a ServerOption that configures the server to log requests to the given writer using the combined log format.
func WithLogger ¶ added in v0.43.0
func WithLogger(l zerolog.Logger) ServerOption
WithLogger returns a ServerOption that configures the server to use the given logger for both server logs and request logs.
Options that set the logger can be given in any order with WithComponent.
func WithMetricsGatherers ¶ added in v0.60.0
func WithMetricsGatherers(gatherers ...prometheus.Gatherer) ServerOption
WithMetricsGatherers replaces the default gatherers used for the /metrics endpoint. The default gathers from the server's own private registry and prometheus.DefaultGatherer.
func WithPrometheusMetrics ¶ added in v0.72.0
func WithPrometheusMetrics() ServerOption
WithPrometheusMetrics returns a ServerOption that serves Prometheus metrics at /metrics. See WithMetricsGatherers for what it serves.
func WithPrometheusRegistry ¶ added in v0.46.0
func WithPrometheusRegistry(r prometheus.Registerer) ServerOption
WithPrometheusRegistry returns a ServerOption that configures the server to register its metrics with the given Prometheus registry.
func WithProxyProtocol ¶ added in v0.72.0
func WithProxyProtocol(policy ProxyProtocolPolicy) ServerOption
WithProxyProtocol returns a ServerOption that makes the server read a PROXY protocol header from each connection, so that it sees the address of the client rather than of the proxy in front of it. policy says what happens to a connection without a header; see ProxyProtocolRequire and ProxyProtocolOptional.
func WithReadiness ¶ added in v0.74.0
func WithReadiness(r ReadinessResource) ServerOption
WithReadiness returns a ServerOption that makes /health/ready report r, such as a service's lifecycle.Readiness, in addition to its resources. r is registered on the server's health registry under "readiness", and registering again replaces it. On a server built by NewOperationalServer that is the primary's registry, so the primary and any other operational server built from it report r too.
func WithStatus ¶ added in v0.72.0
func WithStatus() ServerOption
WithStatus returns a ServerOption that serves the aggregate status of the server's resources and health sources at /status.
func WithTelemetryInstrument ¶ added in v0.46.0
func WithTelemetryInstrument(i Instrument) ServerOption
WithTelemetryInstrument returns a ServerOption that configures the server to use the given telemetry instrument for metrics collection.
type StatusResource ¶
StatusResource is an interface for resources that can report their status.
Source Files
¶
- body_size.go
- client.go
- client_ip.go
- client_ip_config.go
- cookies.go
- cors.go
- enforce_tls_handler.go
- header_marshal.go
- headers.go
- health.go
- http_marshal.go
- logging.go
- metadata.go
- metrics.go
- operational.go
- operations.go
- query_marshal.go
- rate_limiter.go
- request_id.go
- resource.go
- server.go
- server_lifecycle.go
- tls_error_filter.go
- unix.go
Directories
¶
| Path | Synopsis |
|---|---|
|
authz
|
|
|
ip
Package ip provides IP-based authorization middleware.
|
Package ip provides IP-based authorization middleware. |
|
Package json provides utilities for handling JSON requests and responses.
|
Package json provides utilities for handling JSON requests and responses. |
|
Package pprof provides an HTTP resource for exposing pprof debugging endpoints.
|
Package pprof provides an HTTP resource for exposing pprof debugging endpoints. |
|
Package resource provides HTTP resources for wiring into a dioad/net/http server (e.g.
|
Package resource provides HTTP resources for wiring into a dioad/net/http server (e.g. |