middleware

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 24, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const RequestIDHeader = "X-Request-Id"

Variables

This section is empty.

Functions

func Add

func Add(h http.Handler, middlewares ...httputil.Middleware) http.Handler

Add applies one or more middleware functions to a handler in the order they were provided. The first middleware in the list will be the outermost wrapper (executed first).

func CORSWithOptions

func CORSWithOptions(options *CORSOptions) func(http.Handler) http.Handler

CORSWithOptions creates a CORS middleware with the provided configuration. If options is nil, it will use the default CORS settings. If options is an empty struct (CORSOptions{}), it will create a middleware with no CORS headers.

func GetLogEntryMetadata

func GetLogEntryMetadata(ctx context.Context) map[string]interface{}

Retrieve log metadata from context

func LoggerWithOptions

func LoggerWithOptions(options *LoggerOptions) func(http.Handler) http.Handler

func Postgres

func Postgres(pool *pgxpool.Pool, authorizers ...AuthzFunc) func(http.Handler) http.Handler

Postgres middleware attaches a connection from pool to the request context if the http request user is authorized.

func Proxy

func Proxy(target string, opts ProxyOptions) http.HandlerFunc

Proxy creates a reverse proxy handler based on the given target and options

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID middleware generates a unique request ID and tracks request duration.

func Static

func Static(directory string, spaFallback bool, embeddedFS *embed.FS) http.Handler

Static returns an http.Handler that serves static files. If the embeddedFS arg is not nil, it uses serveEmbedded; else, serveLocal

Example usage:

mux := http.NewServeMux()
mux.Handle("GET /", middleware.Static("dist", true, embeddedFS))

This will serve files from the "dist" directory of the embedded file system and use "index.html" as a fallback for routes not directly mapped to a file.

func VerifyBasicAuth

func VerifyBasicAuth(config *BasicAuthConfig, send401Unauthorized ...bool) func(http.Handler) http.Handler

VerifyBasicAuth is a middleware function for basic authentication. By default, it sends a 401 Unauthorized response if credentials are missing or invalid. If send401Unauthorized is false, it allows requests without valid Basic Auth credentials to continue without interference.

func VerifyOIDCToken

func VerifyOIDCToken(config OIDCProviderConfig, send401Unauthorized ...bool) func(http.Handler) http.Handler

VerifyOIDCToken is middleware that verifies OIDC tokens in Authorization headers. By default, it sends a 401 Unauthorized response if the token is missing or invalid. If send401Unauthorized is false, it allows requests with other authorization schemes (e.g., Basic Auth) to continue without interference.

Types

type AuthzFunc

type AuthzFunc func(ctx context.Context) (AuthzResponse, error)

AuthzFunc evaluates context and returns authorization status.

func WithAnonAuthz

func WithAnonAuthz(anonRole string) AuthzFunc

WithAnonAuthz creates auth function using specified role.

func WithBasicAuthz

func WithBasicAuthz() AuthzFunc

WithBasicAuthz creates auth function for Basic Auth.

func WithOIDCAuthz

func WithOIDCAuthz(oidcCfg OIDCProviderConfig, roleClaimKey string) AuthzFunc

WithOIDCAuthz extracts role from OIDC token and adds to context.

type AuthzResponse

type AuthzResponse struct {
	Role    string `json:"role"`
	Allowed bool   `json:"allowed"`
}

AuthzResponse contains authorization result.

type BasicAuthConfig

type BasicAuthConfig struct {
	Credentials map[string]string
}

BasicAuthConfig holds the username-password pairs for basic authentication.

func BasicAuthCreds

func BasicAuthCreds(credentials map[string]string) *BasicAuthConfig

NewBasicAuthCreds creates a new instance of BasicAuthConfig with multiple username/password pairs.

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
}

CORSOptions defines configuration for CORS.

type Cache

type Cache struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Cache is a simple in-memory cache with expiration

func NewCache

func NewCache() *Cache

NewCache creates a new Cache

func (*Cache) CleanupExpired

func (c *Cache) CleanupExpired()

CleanupExpired removes expired items from the cache

func (*Cache) Get

func (c *Cache) Get(key string) (interface{}, bool)

Get retrieves an item from the cache

func (*Cache) Set

func (c *Cache) Set(key string, value interface{}, duration time.Duration)

Set adds an item to the cache with a specified expiration duration

type LoggerOptions

type LoggerOptions struct {
	Logger *zap.Logger
	Format func(reqID string, rec *ResponseRecorder, r *http.Request, latency time.Duration) []zap.Field
}

LoggerOptions defines configuration for the logger middleware.

type OIDCProvider

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

type OIDCProviderConfig

type OIDCProviderConfig struct {
	ClientID      string `json:"client_id"`
	ClientSecret  string `json:"client_secret"`
	Issuer        string `json:"issuer"`
	SkipTLSVerify bool   `json:"skip_tls_verify"`
}

OIDCProviderConfig holds the configuration for the OIDC provider

type ProxyOptions

type ProxyOptions struct {
	TLSConfig     *tls.Config
	TrimPrefix    string
	ForwardedHost string
}

ProxyOptions holds the options for the proxy middleware

type ResponseRecorder

type ResponseRecorder struct {
	http.ResponseWriter
	StatusCode int
	// contains filtered or unexported fields
}

ResponseRecorder is a wrapper for http.ResponseWriter to capture status codes and durations.

func NewResponseRecorder

func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder

func (*ResponseRecorder) Write

func (rr *ResponseRecorder) Write(b []byte) (int, error)

func (*ResponseRecorder) WriteHeader

func (rr *ResponseRecorder) WriteHeader(statusCode int)

Jump to

Keyboard shortcuts

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