middleware

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package middleware provides common middleware functionality for HTTP servers.

Package middleware provides common middleware functionality for HTTP servers.

Package middleware provides common middleware functionality for HTTP servers.

Package middleware provides common middleware functionality for HTTP servers.

Package middleware provides common middleware functionality for HTTP servers. This package contains default implementations and interfaces for middleware components. Framework-specific implementations of these middleware components can be found in their respective packages: - Gin implementation: github.com/tenqube/tenqube-go-http-server/core/gin - Standard HTTP implementation: github.com/tenqube/tenqube-go-http-server/core/std

Package middleware provides common middleware functionality for HTTP servers. This package contains default implementations and interfaces for middleware components. Framework-specific implementations of these middleware components can be found in their respective packages: - Gin implementation: github.com/tenqube/tenqube-go-http-server/core/gin - Standard HTTP implementation: github.com/tenqube/tenqube-go-http-server/core/std

Package middleware provides common middleware functionality for HTTP servers.

Index

Constants

View Source
const UserContextKey contextKey = "user"

Define the context key for the user

Variables

View Source
var ErrForbidden = errors.New("forbidden")

ErrForbidden is returned when the user is authenticated but not authorized

Functions

func APIKeyMiddleware

func APIKeyMiddleware(config *APIKeyConfig) core.HandlerFunc

APIKeyMiddleware returns a middleware function that checks for a valid API key in the x-api-key header. If the API key is missing or invalid, it returns a 401 Unauthorized response.

func AuthMiddleware

func AuthMiddleware(config *AuthConfig) core.HandlerFunc

AuthMiddleware returns a middleware function that checks authorization It supports either Basic HTTP authentication or Bearer JWT tokens based on the configuration

func CORSMiddleware

func CORSMiddleware(config *CORSConfig) core.HandlerFunc

CORSMiddleware returns a middleware function that handles CORS (Cross-Origin Resource Sharing). If AllowedDomains is empty, all domains are allowed. If AllowedDomains contains specific domains, only those domains are allowed.

func DefaultErrorHandlerConfig

func DefaultErrorHandlerConfig() *core.ErrorHandlerConfig

DefaultErrorHandlerConfig returns a default error handler configuration.

func DefaultLoggingConfig

func DefaultLoggingConfig() *core.LoggingConfig

DefaultLoggingConfig returns a default logging configuration.

func DuplicateRequestMiddleware

func DuplicateRequestMiddleware(config *DuplicateRequestConfig) core.HandlerFunc

DuplicateRequestMiddleware returns a middleware function that prevents duplicate requests It generates a request ID using the provided generator, checks if it exists in the storage, and if it does, returns a 409 Conflict response. Otherwise, it saves the ID and continues.

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (interface{}, bool)

GetUserFromContext retrieves the authenticated user from the context

func NewDefaultAPIKeyMiddleware

func NewDefaultAPIKeyMiddleware(apiKey string) core.HandlerFunc

NewDefaultAPIKeyMiddleware returns a middleware function with default configuration and the specified API key. This function creates a default configuration and sets the APIKey to the provided value. Example usage:

s.Use(middleware.NewDefaultAPIKeyMiddleware("your-api-key"))

Or customize the configuration:

config := middleware.DefaultAPIKeyConfig()
config.APIKey = "your-api-key"
config.UnauthorizedMessage = "Custom unauthorized message"
s.Use(middleware.APIKeyMiddleware(config))

Or use the APIKeyMiddleware function directly:

s.Use(middleware.APIKeyMiddleware(&middleware.APIKeyConfig{
	APIKey: "your-api-key",
}))

func NewDefaultBasicAuthMiddleware

func NewDefaultBasicAuthMiddleware(basicAuthLookup BasicAuthUserLookup) core.HandlerFunc

NewDefaultBasicAuthMiddleware returns a middleware function with default Basic authentication configuration. This function creates a default configuration with AuthType set to AuthTypeBasic and sets the provided parameter. Example usage:

s.Use(middleware.NewDefaultBasicAuthMiddleware(myBasicAuthLookup))

Or customize the configuration:

config := middleware.DefaultAuthConfig()
config.AuthType = middleware.AuthTypeBasic
config.BasicAuthLookup = myBasicAuthLookup
config.UnauthorizedMessage = "Custom unauthorized message"
s.Use(middleware.AuthMiddleware(config))

func NewDefaultCORSMiddleware

func NewDefaultCORSMiddleware() core.HandlerFunc

NewDefaultCORSMiddleware returns a middleware function with default configuration. This function uses the DefaultCORSConfig which allows all domains. Example usage:

s.Use(middleware.NewDefaultCORSMiddleware())

Or customize the configuration:

config := middleware.DefaultCORSConfig()
config.AllowedDomains = []string{"https://example.com"}
s.Use(middleware.CORSMiddleware(config))

func NewDefaultConsoleLogging

func NewDefaultConsoleLogging(skipPaths []string, customFields map[string]string) *core.LoggingConfig

NewDefaultConsoleLogging returns a logging configuration for console-only logging with the specified ignore path list and custom fields.

Example usage:

config := middleware.NewDefaultConsoleLogging(
	[]string{"/health", "/metrics"},
	map[string]string{"version": "1.0.0", "environment": "production"}
)
s.Use(middleware.LoggingMiddleware(config))

func NewDefaultDuplicateRequestMiddleware

func NewDefaultDuplicateRequestMiddleware() core.HandlerFunc

NewDefaultDuplicateRequestMiddleware returns a middleware function with default configuration. Note: This function panics because DuplicateRequestMiddleware requires additional configuration: - RequestIDGenerator must be provided - RequestIDStorage must be provided You must set these fields in the configuration before using this middleware. Example usage:

config := middleware.DefaultDuplicateRequestConfig()
config.RequestIDGenerator = myRequestIDGenerator
config.RequestIDStorage = myRequestIDStorage
s.Use(middleware.DuplicateRequestMiddleware(config))

Or use the DuplicateRequestMiddleware function directly:

s.Use(middleware.DuplicateRequestMiddleware(&middleware.DuplicateRequestConfig{
	RequestIDGenerator: myRequestIDGenerator,
	RequestIDStorage:   myRequestIDStorage,
	ConflictMessage:    "Custom conflict message",
}))

func NewDefaultJWTAuthMiddleware

func NewDefaultJWTAuthMiddleware(jwtLookup JWTUserLookup, jwtSecret string) core.HandlerFunc

NewDefaultJWTAuthMiddleware returns a middleware function with default JWT authentication configuration. This function creates a default configuration with AuthType set to AuthTypeJWT and sets the provided parameters. Example usage:

s.Use(middleware.NewDefaultJWTAuthMiddleware(myJWTLookup, "your-jwt-secret"))

Or customize the configuration:

config := middleware.DefaultAuthConfig()
config.AuthType = middleware.AuthTypeJWT
config.JWTLookup = myJWTLookup
config.JWTSecret = "your-jwt-secret"
config.UnauthorizedMessage = "Custom unauthorized message"
s.Use(middleware.AuthMiddleware(config))

func NewDefaultTimeoutMiddleware

func NewDefaultTimeoutMiddleware() core.HandlerFunc

NewDefaultTimeoutMiddleware returns a middleware function with default configuration. This function uses the DefaultTimeoutConfig which sets a default timeout of 2 seconds. Example usage:

s.Use(middleware.NewDefaultTimeoutMiddleware())

Or customize the configuration:

config := middleware.DefaultTimeoutConfig()
config.Timeout = 5 * time.Second
s.Use(middleware.TimeoutMiddleware(config))

func TimeoutMiddleware

func TimeoutMiddleware(config *TimeoutConfig) core.HandlerFunc

TimeoutMiddleware returns a middleware function that times out requests after a specified duration. If the handler doesn't respond within the timeout period, it returns a 503 Service Unavailable response.

Types

type APIKeyConfig

type APIKeyConfig struct {
	// APIKey is the expected API key value.
	// This value will be compared against the x-api-key header.
	APIKey string

	// Optional: custom error message
	UnauthorizedMessage string
}

APIKeyConfig holds configuration for the API key middleware.

func DefaultAPIKeyConfig

func DefaultAPIKeyConfig() *APIKeyConfig

DefaultAPIKeyConfig returns a default API key configuration.

type ApiLog

type ApiLog struct {
	ClientIp      string            `json:"client_ip"`
	Timestamp     string            `json:"timestamp"`
	Method        string            `json:"method"`
	Path          string            `json:"path"`
	Protocol      string            `json:"protocol"`
	StatusCode    int               `json:"status_code"`
	Latency       int64             `json:"latency"`
	UserAgent     string            `json:"user_agent"`
	Error         string            `json:"error"`
	RequestId     string            `json:"request_id"`
	Authorization string            `json:"authorization"`
	CustomFields  map[string]string `json:"custom_fields,omitempty"`
}

ApiLog represents the structure of a log entry for API requests.

type AuthConfig

type AuthConfig struct {
	// UserLookup is the implementation of UserLookupInterface
	// This is kept for backward compatibility
	UserLookup UserLookupInterface

	// BasicAuthLookup is the implementation of BasicAuthUserLookup
	// Used when AuthType is AuthTypeBasic
	BasicAuthLookup BasicAuthUserLookup

	// JWTLookup is the implementation of JWTUserLookup
	// Used when AuthType is AuthTypeJWT
	JWTLookup JWTUserLookup

	// AuthType specifies which authentication method to use (basic or jwt)
	// If not specified, it defaults to jwt
	AuthType AuthType

	// JWTSecret is the secret key used to validate JWT tokens
	// Required when AuthType is AuthTypeJWT
	JWTSecret string

	// Optional: custom error messages
	UnauthorizedMessage string
	ForbiddenMessage    string

	// SkipPaths is a list of paths to ignore for authentication
	SkipPaths []string
}

AuthConfig holds configuration for the authorization middleware

func DefaultAuthConfig

func DefaultAuthConfig() *AuthConfig

DefaultAuthConfig returns a default auth configuration

type AuthType

type AuthType string

AuthType represents the type of authentication to use

const (
	// AuthTypeBasic represents HTTP Basic authentication
	AuthTypeBasic AuthType = "basic"
	// AuthTypeJWT represents JWT Bearer token authentication
	AuthTypeJWT AuthType = "jwt"
)

type BaseLoggingMiddleware

type BaseLoggingMiddleware struct{}

BaseLoggingMiddleware provides common functionality for logging middleware implementations. This struct is embedded by framework-specific logging middleware implementations: - Gin implementation: github.com/tenqube/tenqube-go-http-server/core/gin.LoggingMiddleware - Standard HTTP implementation: github.com/tenqube/tenqube-go-http-server/core/std.LoggingMiddleware It provides methods for creating and processing log entries that are used by all implementations.

func (*BaseLoggingMiddleware) CreateLogEntry

func (m *BaseLoggingMiddleware) CreateLogEntry(req *http.Request, statusCode int, latency int64, requestID string, config *core.LoggingConfig) *ApiLog

CreateLogEntry creates a log entry from the request details.

func (*BaseLoggingMiddleware) ProcessLog

func (m *BaseLoggingMiddleware) ProcessLog(logEntry *ApiLog, config *core.LoggingConfig)

ProcessLog logs the entry to the console and sends it to the remote URL if configured.

type BasicAuthUserLookup

type BasicAuthUserLookup interface {
	// LookupUserByBasicAuth looks up a user by username and password
	LookupUserByBasicAuth(username, password string) (interface{}, error)
}

BasicAuthUserLookup defines the interface for looking up users based on Basic Auth credentials

type CORSConfig

type CORSConfig struct {
	// AllowedDomains is a list of domains that are allowed to access the API.
	// If empty, all domains are allowed.
	AllowedDomains []string

	// AllowedMethods is a list of HTTP methods that are allowed.
	// Default: "GET, POST, PUT, DELETE, OPTIONS, PATCH"
	AllowedMethods string

	// AllowedHeaders is a list of HTTP headers that are allowed.
	// Default: "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, X-Requested-With"
	AllowedHeaders string

	// AllowCredentials indicates whether the request can include user credentials.
	// Default: true
	AllowCredentials bool

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
	// Default: 86400 (24 hours)
	MaxAge int
}

CORSConfig holds configuration for the CORS middleware.

func DefaultCORSConfig

func DefaultCORSConfig() *CORSConfig

DefaultCORSConfig returns a default CORS configuration.

type DuplicateRequestConfig

type DuplicateRequestConfig struct {
	// RequestIDGenerator is the implementation of RequestIDGenerator
	RequestIDGenerator RequestIDGenerator

	// RequestIDStorage is the implementation of RequestIDStorage
	RequestIDStorage RequestIDStorage

	// Optional: custom error message
	ConflictMessage string
}

DuplicateRequestConfig holds configuration for the duplicate request prevention middleware

func DefaultDuplicateRequestConfig

func DefaultDuplicateRequestConfig() *DuplicateRequestConfig

DefaultDuplicateRequestConfig returns a default duplicate request configuration

type IErrorHandlerMiddleware

type IErrorHandlerMiddleware interface {
	// Middleware returns a middleware function that handles errors.
	Middleware(config *core.ErrorHandlerConfig) core.HandlerFunc
}

IErrorHandlerMiddleware is an interface for error handler middleware implementations. Each framework (Gin, StdHTTP) provides its own implementation of this interface: - Gin implementation: github.com/tenqube/tenqube-go-http-server/core/gin.ErrorHandlerMiddleware - Standard HTTP implementation: github.com/tenqube/tenqube-go-http-server/core/std.ErrorHandlerMiddleware

type JWTUserLookup

type JWTUserLookup interface {
	// LookupUserByJWT looks up a user by JWT claims
	LookupUserByJWT(claims MapClaims) (interface{}, error)
}

JWTUserLookup defines the interface for looking up users based on JWT claims

type MapClaims

type MapClaims map[string]interface{}

MapClaims represents JWT claims as a map

type RequestIDGenerator

type RequestIDGenerator interface {
	// GenerateRequestID generates a unique request ID from the context
	GenerateRequestID(ctx context.Context) (string, error)
}

RequestIDGenerator defines the interface for generating request IDs

type RequestIDStorage

type RequestIDStorage interface {
	// CheckRequestID checks if a request ID exists in the storage
	CheckRequestID(requestID string) (bool, error)

	// SaveRequestID saves a request ID to the storage
	SaveRequestID(requestID string) error
}

RequestIDStorage defines the interface for checking and storing request IDs

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriterWrapper is a wrapper for http.ResponseWriter that captures the status code.

func (*ResponseWriterWrapper) CloseNotify

func (w *ResponseWriterWrapper) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to pass through to the underlying ResponseWriter.

func (*ResponseWriterWrapper) Flush

func (w *ResponseWriterWrapper) Flush()

Flush implements the http.Flusher interface to pass through to the underlying ResponseWriter.

func (*ResponseWriterWrapper) Hijack

Hijack implements the http.Hijacker interface to pass through to the underlying ResponseWriter.

func (*ResponseWriterWrapper) Push

func (w *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error

Push implements the http.Pusher interface to pass through to the underlying ResponseWriter.

func (*ResponseWriterWrapper) Status

func (w *ResponseWriterWrapper) Status() int

Status returns the captured status code.

func (*ResponseWriterWrapper) Write

func (w *ResponseWriterWrapper) Write(b []byte) (int, error)

Write captures the status code (if not already set) and calls the underlying ResponseWriter's Write.

func (*ResponseWriterWrapper) WriteHeader

func (w *ResponseWriterWrapper) WriteHeader(code int)

WriteHeader captures the status code and calls the underlying ResponseWriter's WriteHeader.

type TimeoutConfig

type TimeoutConfig struct {
	// Timeout is the maximum duration to wait for a response.
	// If not set, it defaults to 2 seconds.
	Timeout time.Duration
}

TimeoutConfig holds configuration for the timeout middleware.

func DefaultTimeoutConfig

func DefaultTimeoutConfig() *TimeoutConfig

DefaultTimeoutConfig returns a default timeout configuration.

type UserLookupInterface

type UserLookupInterface interface {
	BasicAuthUserLookup
	JWTUserLookup
}

UserLookupInterface defines the interface for looking up users based on credentials This is kept for backward compatibility

Directories

Path Synopsis
Package errors provides error classes for HTTP status codes.
Package errors provides error classes for HTTP status codes.

Jump to

Keyboard shortcuts

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