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.HeaderMarshalOptions{
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 ¶
- func AddMapToHTTPHeader(baseHeaders http.Header, headerMap map[string]string) http.Header
- func CORSAllowLocalhostOrigin(origin string) bool
- func CORSHandler(options cors.Options) (mux.MiddlewareFunc, error)
- func CreateHTTPHeaderFromMap(headerMap map[string]string) http.Header
- func MarshalHeader(v interface{}, opts HeaderMarshalOptions) (http.Header, error)
- func NewPersistentCookieStore(config CookieConfig) (*sessions.CookieStore, error)
- func NewSessionCookieStore(config CookieConfig) (*sessions.CookieStore, error)
- func NewUnixSocketClient(path string) *http.Client
- func OAuth2ValidatorHandler(v []oidc.ValidatorConfig) (mux.MiddlewareFunc, error)
- func StandardLogger(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger
- func UnmarshalHeader(header http.Header, v interface{}, opts HeaderMarshalOptions) error
- type Client
- type ClientConfig
- type Config
- type CookieConfig
- type DefaultResource
- type EnforceTLSHandler
- type HandlerWrapper
- type HeaderMarshalOptions
- type LogLevelSetter
- type MetricSet
- type PathResource
- type RateLimiter
- 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) AddResource(pathPrefix string, r Resource, middlewares ...mux.MiddlewareFunc)
- func (s *Server) AddRootResource(r RootResource)
- func (s *Server) AddStatusStaticMetadataItem(key string, value any)
- func (s *Server) ListenAndServe() error
- func (s *Server) ListenAndServeTLS(tlsConfig *tls.Config) error
- 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) Use(middlewares ...mux.MiddlewareFunc)
- type ServerOption
- func WithCORS(options cors.Options) ServerOption
- func WithLogWriter(w io.Writer) ServerOption
- func WithLogger(l zerolog.Logger) ServerOption
- func WithOAuth2Validator(v []oidc.ValidatorConfig) ServerOption
- func WithPrometheusRegistry(r prometheus.Registerer) ServerOption
- func WithServerAuth(cfg auth.ServerConfig) ServerOption
- func WithTelemetryInstrument(i middleware.Instrument) ServerOption
- type StatusResource
- type StructuredLoggerFormatter
- type UseResource
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddMapToHTTPHeader ¶
AddMapToHTTPHeader adds a map[string]string to an existing http.Header
func CORSAllowLocalhostOrigin ¶ added in v0.50.4
CORSAllowLocalhostOrigin returns true if the given origin is a localhost origin.
func CORSHandler ¶ added in v0.50.4
func CORSHandler(options cors.Options) (mux.MiddlewareFunc, error)
CORSHandler returns a middleware that handles Cross-Origin Resource Sharing (CORS).
func CreateHTTPHeaderFromMap ¶
CreateHTTPHeaderFromMap creates a new http.Header from a map[string]string
func MarshalHeader ¶ added in v0.52.0
func MarshalHeader(v interface{}, opts HeaderMarshalOptions) (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 field 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 DefaultHeaderMarshalOptions which doesn't add any prefix or struct name.
// Field names will be determined by the `header` tag if present,
// or automatically converted to kebab-case.
header, err := dhttp.MarshalHeader(user, dhttp.DefaultHeaderMarshalOptions())
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 field will be ignored
}
metadata := Metadata{
RequestID: "req-789",
TraceID: "trace-abc",
Internal: "should-not-appear",
}
opts := dhttp.DefaultHeaderMarshalOptions()
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.HeaderMarshalOptions{
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.DefaultHeaderMarshalOptions()
// 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.HeaderMarshalOptions{
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-Api-Key: %s\n", headers.Get("X-Api-Key"))
fmt.Printf(" X-Region: %s\n", headers.Get("X-Region"))
}
Output: Headers without struct name: X-Api-Key: secret-key X-Region: us-west-2
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 OAuth2ValidatorHandler ¶ added in v0.50.4
func OAuth2ValidatorHandler(v []oidc.ValidatorConfig) (mux.MiddlewareFunc, error)
OAuth2ValidatorHandler returns a middleware that validates OAuth2 tokens using the provided configurations.
func StandardLogger ¶ added in v0.36.1
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 interface{}, opts HeaderMarshalOptions) error
UnmarshalHeader decodes an http.Header into a struct using the provided options.
RFC 9110 Compliance: Multiple header field 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
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.DefaultHeaderMarshalOptions())
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.HeaderMarshalOptions{
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-Tenant-Id", "tenant-123")
req.Header.Set("X-Context-User-Role", "admin")
// Create a response recorder
w := httptest.NewRecorder()
// Process the request
wrappedHandler.ServeHTTP(w, req)
}
Output: Processing request for tenant: tenant-123, role: admin
Types ¶
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.
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
}
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 DefaultResource ¶
DefaultResource is an interface for resources that can register their routes on a router.
type EnforceTLSHandler ¶ added in v0.37.0
type EnforceTLSHandler struct {
EnforceTLS bool
}
EnforceTLSHandler wraps an HTTP handler to enforce TLS connections.
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.
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 HeaderMarshalOptions ¶ added in v0.52.0
type HeaderMarshalOptions struct {
// Prefix is prepended to all header names (e.g., "X" results in "X-Field-Name")
Prefix string
// IncludeStructName includes the struct type name in the header (e.g., "X-Example-Field-Name")
IncludeStructName bool
}
HeaderMarshalOptions configures how structs are marshaled to and from http.Header
func DefaultHeaderMarshalOptions ¶ added in v0.52.0
func DefaultHeaderMarshalOptions() HeaderMarshalOptions
DefaultHeaderMarshalOptions returns default options with no prefix and no struct name
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
}
func NewMetricSet ¶
func NewMetricSet(r *prometheus.Registry) *MetricSet
func (*MetricSet) Middleware ¶
Middleware - to make it a middleware for mux probably a better way. TODO: need to extract this from this struct to remove the coupling with mux
func (*MetricSet) Register ¶
func (m *MetricSet) Register(r prometheus.Registerer)
type PathResource ¶
PathResource is an interface for resources that can register their routes on a router with a path prefix.
type RateLimiter ¶ added in v0.53.0
type RateLimiter struct {
*ratelimit.RateLimiter
}
RateLimiter provides per-principal rate limiting for HTTP requests.
func NewRateLimiter ¶ added in v0.53.0
func NewRateLimiter(requestsPerSecond float64, burst int, logger zerolog.Logger) *RateLimiter
NewRateLimiter creates a new rate limiter with static limits. requestsPerSecond: allowed requests per second per principal burst: maximum burst size
func NewRateLimiterWithSource ¶ added in v0.53.0
func NewRateLimiterWithSource(source ratelimit.RateLimitSource, logger zerolog.Logger) *RateLimiter
NewRateLimiterWithSource creates a new rate limiter with a custom rate limit source.
func (*RateLimiter) Middleware ¶ added in v0.53.0
Middleware returns an HTTP middleware for rate limiting.
func (*RateLimiter) MiddlewareFromContext ¶ added in v0.53.0
func (rl *RateLimiter) MiddlewareFromContext(contextKey interface{}) func(http.Handler) http.Handler
MiddlewareFromContext returns an HTTP middleware that extracts the principal from context.
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
// Router is the main router for the server
Router *mux.Router
// 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
// 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 ¶
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 ...mux.MiddlewareFunc)
AddResource adds a resource to the server at the specified path prefix The resource can implement either PathResource or DefaultResource to register its routes Optional middlewares can be provided to be applied 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 ¶
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) 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) 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
func (*Server) Use ¶ added in v0.43.0
func (s *Server) Use(middlewares ...mux.MiddlewareFunc)
Use adds middleware to the server's router Any nil middlewares will be filtered out
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() (interface{}, 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.
type UseResource ¶ added in v0.43.1
type UseResource interface {
Use(...mux.MiddlewareFunc) UseResource
}
UseResource is an interface for resources that support applying middleware.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth provides HTTP authentication utilities and interfaces.
|
Package auth provides HTTP authentication utilities and interfaces. |
|
basic
Package basic provides HTTP Basic authentication middleware and utilities.
|
Package basic provides HTTP Basic authentication middleware and utilities. |
|
context
Package context provides utilities for managing authentication information in context.
|
Package context provides utilities for managing authentication information in context. |
|
github
Package github provides GitHub-based authentication middleware.
|
Package github provides GitHub-based authentication middleware. |
|
hmac
Package hmac provides HMAC-based authentication middleware.
|
Package hmac provides HMAC-based authentication middleware. |
|
oidc
Package oidc provides HTTP authentication using OpenID Connect.
|
Package oidc provides HTTP authentication using OpenID Connect. |
|
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. |