http

package
v0.50.3 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

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 CreateHTTPHeaderFromMap

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

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

func NewPersistentCookieStore

func NewPersistentCookieStore(config CookieConfig) (*sessions.CookieStore, error)

func NewSessionCookieStore

func NewSessionCookieStore(config CookieConfig) (*sessions.CookieStore, error)

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.

Types

type Client

type Client struct {
	Config *ClientConfig
}

func NewClient

func NewClient(config *ClientConfig) *Client

func NewDefaultClient

func NewDefaultClient() *Client

func (*Client) Request

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

func (*Client) ResolveRelativeRequestPath

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

type ClientConfig

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

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"`
}

type DefaultResource

type DefaultResource interface {
	RegisterRoutes(*mux.Router)
}

type EnforceTLSHandler added in v0.37.0

type EnforceTLSHandler struct {
	EnforceTLS bool
}

func (*EnforceTLSHandler) Wrap added in v0.37.0

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

type HandlerWrapper

type HandlerWrapper func(next http.Handler) 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 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

func (m *MetricSet) Middleware(next http.Handler) http.Handler

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

type PathResource interface {
	RegisterRoutesWithPrefix(*mux.Router, string)
}

type Resource

type Resource interface{}

type RootResource

type RootResource interface {
	// Resource
	Index() http.HandlerFunc
}

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 NewServerWithLogger

func NewServerWithLogger(config Config, logger zerolog.Logger) *Server

NewServerWithLogger creates a new HTTP server with the given configuration and logger Deprecated: Use NewServer with WithLogger instead

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

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

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

type StructuredLoggerFormatter added in v0.36.1

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

type UseResource added in v0.43.1

type UseResource interface {
	Use(...mux.MiddlewareFunc) UseResource
}

Directories

Path Synopsis
jwt
authz
ip
jwt

Jump to

Keyboard shortcuts

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