http

package
v0.55.1 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

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

Examples

Constants

View Source
const (
	// DefaultMaxBodyBytes is the default maximum request body size (1MB).
	DefaultMaxBodyBytes = 1 * 1024 * 1024
)
View Source
const (
	// HeaderMarshalTagName is the struct tag name used for marshaling/unmarshaling HTTP headers
	HeaderMarshalTagName = "header"
)
View Source
const (
	// QueryMarshalTagName is the struct tag name used for marshaling/unmarshaling URI query parameters
	QueryMarshalTagName = "query"
)

Variables

View Source
var (
	DefaultRequestsPerSecond = float64(10) // default to 10 rps
	DefaultBurst             = 20          // DefaultBurst specifies the default maximum burst size for rate limiting.
)

Functions

func AddMapToHTTPHeader

func AddMapToHTTPHeader(baseHeaders http.Header, headerMap map[string]string) http.Header

AddMapToHTTPHeader adds a map[string]string to an existing http.Header

func CORSAllowLocalhostOrigin added in v0.50.4

func CORSAllowLocalhostOrigin(origin string) bool

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

func ClientIPFromContext(ctx context.Context) (string, bool)

ClientIPFromContext retrieves the client IP address from the context.

func ClientIPPrincipalFunc added in v0.54.0

func ClientIPPrincipalFunc(r *http.Request) (string, error)

ClientIPPrincipalFunc is a default PrincipalFunc that extracts the client's IP address from the request for rate limiting purposes.

func ContextWithClientIP added in v0.54.0

func ContextWithClientIP(ctx context.Context, r *http.Request) context.Context

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

func CreateHTTPHeaderFromMap(headerMap map[string]string) http.Header

CreateHTTPHeaderFromMap creates a new http.Header from a map[string]string

func GetClientIP added in v0.54.0

func GetClientIP(r *http.Request) string

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.

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 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

func NewUnixSocketClient(path string) *http.Client

func StandardLogger added in v0.36.1

func StandardLogger(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger

StandardLogger creates a zerolog.Logger with standard fields for HTTP access logging.

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 (
	"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
			if err := dhttp.UnmarshalHeader(r.Header, &ctx, opts); 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, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	// Wrap with middleware
	wrappedHandler := middleware(handler)

	// Simulate a request with headers
	req, _ := http.NewRequest("GET", "/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", &params, 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

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 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
	Logger       zerolog.Logger
}

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.

type BodySizeLimiterOpt added in v0.54.0

type BodySizeLimiterOpt func(*BodySizeLimiter)

BodySizeLimiterOpt defines a functional option for configuring the BodySizeLimiter.

func WithBodySizeLimiterLogger added in v0.54.0

func WithBodySizeLimiterLogger(logger zerolog.Logger) BodySizeLimiterOpt

WithBodySizeLimiterLogger sets a custom logger for 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 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

NewClient creates a new HTTP client with the provided configuration.

func NewDefaultClient

func NewDefaultClient() *Client

NewDefaultClient creates a new HTTP client with default configuration.

func (*Client) Request

func (c *Client) Request(req *http.Request) (*http.Response, error)

Request performs an HTTP request with client configuration and authentication.

func (*Client) ResolveRelativeRequestPath

func (c *Client) ResolveRelativeRequestPath(requestPath string) (*url.URL, error)

ResolveRelativeRequestPath resolves a relative request path against the client's base URL.

type ClientConfig

type ClientConfig struct {
	BaseURL    *url.URL
	Client     *http.Client
	UserAgent  string
	AuthConfig auth.ClientConfig
}

ClientConfig describes the configuration for an HTTP client.

type Config

type Config struct {
	// ListenAddress is the address to listen on, e.g. ":8080"
	ListenAddress string
	// EnablePrometheusMetrics enables the /metrics endpoint for Prometheus metrics
	EnablePrometheusMetrics bool
	// EnableDebug enables the /debug endpoint for pprof debugging
	EnableDebug bool
	// EnableStatus enables the /status endpoint for server status
	EnableStatus bool
	// EnableProxyProtocol enables the PROXY protocol for client IP forwarding
	EnableProxyProtocol bool
	// TLSConfig is the TLS configuration for the server
	TLSConfig *tls.Config
	// AuthConfig is the authentication configuration for the server
	AuthConfig auth.ServerConfig
	// EnableHealth enables the /health/live and /health/ready endpoints for health checks
	EnableHealth bool
}

Config represents the configuration for an HTTP server

type CookieConfig

type CookieConfig struct {
	Base64AuthenticationKey string `mapstructure:"base64-authentication-key"`
	Base64EncryptionKey     string `mapstructure:"base64-encryption-key"`
	MaxAge                  int    `mapstructure:"max-age"`
	Domain                  string `mapstructure:"domain"`
}

CookieConfig describes the configuration for HTTP cookies.

type EnforceTLSHandler added in v0.37.0

type EnforceTLSHandler struct {
	EnforceTLS bool
}

EnforceTLSHandler wraps an HTTP handler to enforce TLS connections.

func (*EnforceTLSHandler) Wrap added in v0.37.0

func (h *EnforceTLSHandler) Wrap(handler http.Handler) http.Handler

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
}

func DefaultHTTPMarshalOptions added in v0.54.0

func DefaultHTTPMarshalOptions() HTTPMarshalOptions

DefaultHTTPMarshalOptions returns default options with no prefix and no struct name

type HandlerWrapper

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

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.

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.

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.

type LivenessResource added in v0.54.0

type LivenessResource interface {
	Live() error
}

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 MetricSet

type MetricSet struct {
	RequestCounter    *prometheus.CounterVec
	RequestDuration   *prometheus.HistogramVec
	RequestSize       *prometheus.HistogramVec
	ResponseSize      *prometheus.HistogramVec
	InFlightGauge     prometheus.Gauge
	RateLimitRequests *prometheus.CounterVec
	// contains filtered or unexported fields
}

func NewMetricSet

func NewMetricSet(r *prometheus.Registry) *MetricSet

func (*MetricSet) Middleware

func (m *MetricSet) Middleware(mux *http.ServeMux, next http.Handler) http.Handler

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)

type Middleware added in v0.55.0

type Middleware func(http.Handler) http.Handler

Middleware is a standard function signature for HTTP middleware.

func CORSHandler added in v0.50.4

func CORSHandler(options cors.Options) (Middleware, error)

CORSHandler returns a middleware that handles Cross-Origin Resource Sharing (CORS).

func OAuth2ValidatorHandler added in v0.50.4

func OAuth2ValidatorHandler(v []oidc.ValidatorConfig) (Middleware, error)

OAuth2ValidatorHandler returns a middleware that validates OAuth2 tokens using the provided configurations.

type PrincipalFunc added in v0.54.0

type PrincipalFunc func(*http.Request) (string, error)

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

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

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.

type RateLimiterOption added in v0.54.0

type RateLimiterOption func(*RateLimiter)

type ReadinessResource added in v0.54.0

type ReadinessResource interface {
	Ready() (any, error)
}

ReadinessResource is an interface for resources that can report their readiness.

type Resource

type Resource interface {
	Handler() http.Handler
}

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 {
	// 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
	// Mux is the main router for the server
	Mux *http.ServeMux
	// 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
	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 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

func (*Server) AddHandler

func (s *Server) AddHandler(path string, handler http.Handler)

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) 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 The root resource's Index method will be called for any path that doesn't match other routes

func (*Server) AddStatusStaticMetadataItem

func (s *Server) AddStatusStaticMetadataItem(key string, value any)

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 middleware.Instrument)

ConfigureTelemetryInstrument configures the server with the given telemetry instrument

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

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

func (s *Server) ListenAndServeTLS(tlsConfig *tls.Config) error

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) 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

func (s *Server) Serve(ln net.Listener) error

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

func (s *Server) ServeTLS(ln net.Listener) error

ServeTLS is a convenience method that calls Serve It's provided for compatibility with the http.Server interface

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

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

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 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

func WithOAuth2Validator added in v0.43.0

func WithOAuth2Validator(v []oidc.ValidatorConfig) ServerOption

WithOAuth2Validator returns a ServerOption that configures the server to use OAuth2 validation for authentication using the given validator configurations

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 WithServerAuth added in v0.46.0

func WithServerAuth(cfg auth.ServerConfig) ServerOption

WithServerAuth returns a ServerOption that configures the server to use the given authentication configuration

func WithTelemetryInstrument added in v0.46.0

func WithTelemetryInstrument(i middleware.Instrument) ServerOption

WithTelemetryInstrument returns a ServerOption that configures the server to use the given telemetry instrument for metrics collection

type StatusResource

type StatusResource interface {
	Status() (any, error)
}

StatusResource is an interface for resources that can report their status.

type StructuredLoggerFormatter added in v0.36.1

type StructuredLoggerFormatter func(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger

StructuredLoggerFormatter is a function type that formats HTTP request logs in a structured format.

Directories

Path Synopsis
authz
ip
Package ip provides IP-based authorization middleware.
Package ip provides IP-based authorization middleware.
principal
Package principal provides principal-based authorization middleware.
Package principal provides principal-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.

Jump to

Keyboard shortcuts

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