middleware

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	RouteManager *routeParamsManager

	CommonMiddlewaresChan = make(chan gin.HandlerFunc, 1024)
	AuthMiddlewaresChan   = make(chan gin.HandlerFunc, 1024)
)

Functions

func AddSpanEvent

func AddSpanEvent(c *gin.Context, name string, attrs ...attribute.KeyValue)

AddSpanEvent adds an event to the current span

func AddSpanTags

func AddSpanTags(c *gin.Context, tags map[string]any)

AddSpanTags adds custom tags to the current span

func AuthMarker added in v0.9.6

func AuthMarker() gin.HandlerFunc

AuthMarker is a middleware that marks the current route as requiring authentication. This middleware sets a flag in gin.Context to indicate that the current route requires authentication.

func Authz

func Authz() gin.HandlerFunc

Authz authorizes requests using RBAC. It derives subject from context or headers, falling back to system user.

func BaseAuth

func BaseAuth() gin.HandlerFunc

func CircuitBreaker

func CircuitBreaker() gin.HandlerFunc

func Cors

func Cors() gin.HandlerFunc

func Delay added in v0.10.1

func Delay(duration time.Duration) gin.HandlerFunc

Delay returns a middleware that adds a fixed delay before processing the request. This is primarily used for testing purposes to simulate network latency or slow responses.

Parameters:

  • duration: The delay duration to add before processing the request

Returns:

  • A gin.HandlerFunc that adds the specified delay

Example:

// Add a 100ms delay to all requests
router.Use(middleware.Delay(100 * time.Millisecond))

// Add a 1 second delay
router.Use(middleware.Delay(1 * time.Second))

func DelayRandom added in v0.10.1

func DelayRandom(minDuration, maxDuration time.Duration) gin.HandlerFunc

DelayRandom returns a middleware that adds a random delay within the specified range before processing the request. This is primarily used for testing purposes to simulate variable network latency or slow responses.

Parameters:

  • minDuration: The minimum delay duration
  • maxDuration: The maximum delay duration

Returns:

  • A gin.HandlerFunc that adds a random delay between minDuration and maxDuration

Example:

// Add a random delay between 0 and 3000ms
router.Use(middleware.DelayRandom(0, 3000*time.Millisecond))

// Add a random delay between 100ms and 500ms
router.Use(middleware.DelayRandom(100*time.Millisecond, 500*time.Millisecond))

func DelayWithConfig added in v0.10.1

func DelayWithConfig(delayFunc func(*gin.Context) time.Duration) gin.HandlerFunc

DelayWithConfig returns a middleware that adds a configurable delay based on request properties. This allows for more flexible testing scenarios, such as different delays for different paths or methods.

Parameters:

  • delayFunc: A function that determines the delay duration based on the request context

Returns:

  • A gin.HandlerFunc that adds the delay determined by delayFunc

Example:

// Add delay based on path
router.Use(middleware.DelayWithConfig(func(c *gin.Context) time.Duration {
	if strings.HasPrefix(c.Request.URL.Path, "/api/slow") {
		return 2 * time.Second
	}
	return 100 * time.Millisecond
}))

func GetSpanFromContext

func GetSpanFromContext(c *gin.Context) trace.Span

GetSpanFromContext retrieves the OpenTelemetry span from Gin context

func Gzip

func Gzip() gin.HandlerFunc

func IAMSession added in v0.10.1

func IAMSession() gin.HandlerFunc

func IPBlacklist added in v0.10.1

func IPBlacklist(blacklist []string) gin.HandlerFunc

IPBlacklist returns a middleware that blocks requests from IP addresses in the blacklist.

Parameters:

  • blacklist: List of blocked IP addresses or CIDR ranges (e.g., "192.168.1.100", "10.0.0.0/8")

Returns:

  • A gin.HandlerFunc that enforces IP blacklist

Example:

// Block specific IPs
router.Use(middleware.IPBlacklist([]string{"192.168.1.100", "10.0.0.0/8"}))

// Block known malicious IPs
router.Use(middleware.IPBlacklist([]string{"1.2.3.4", "5.6.7.8"}))

func IPFilter added in v0.10.1

func IPFilter(config *IPFilterConfig) gin.HandlerFunc

IPFilter returns a middleware that filters requests based on IP whitelist and blacklist. Blacklist takes precedence over whitelist.

Parameters:

  • config: Configuration for IP filtering

Returns:

  • A gin.HandlerFunc that enforces IP filtering rules

Example:

// Use both whitelist and blacklist
router.Use(middleware.IPFilter(&middleware.IPFilterConfig{
	Whitelist: []string{"192.168.0.0/16"},
	Blacklist: []string{"192.168.1.100"},
}))

func IPWhitelist added in v0.10.1

func IPWhitelist(whitelist []string) gin.HandlerFunc

IPWhitelist returns a middleware that only allows requests from IP addresses in the whitelist.

Parameters:

  • whitelist: List of allowed IP addresses or CIDR ranges (e.g., "192.168.1.1", "10.0.0.0/8")

Returns:

  • A gin.HandlerFunc that enforces IP whitelist

Example:

// Allow only specific IPs
router.Use(middleware.IPWhitelist([]string{"192.168.1.1", "10.0.0.0/8"}))

// Allow only localhost
router.Use(middleware.IPWhitelist([]string{"127.0.0.1", "::1"}))

func Init

func Init() (err error)

func JwtAuth

func JwtAuth() gin.HandlerFunc

JwtAuth 效果如下: 1.重复登录之后,会刷新 accessToken, refreshToken, 之后老的 accessToken 是失效 2.换浏览器、换操作系统都需要重新登录,重新登录之后会挤掉其他设备、浏览器的登录

func Logger

func Logger(filename ...string) gin.HandlerFunc

func NewRouteParamsManager

func NewRouteParamsManager() *routeParamsManager

func RateLimiter

func RateLimiter() gin.HandlerFunc

func RecordError

func RecordError(c *gin.Context, err error)

RecordError records an error in the current span

func Recovery

func Recovery(filename string) gin.HandlerFunc

func RecoveryWithTracing

func RecoveryWithTracing(logger *zap.Logger, stack bool) gin.HandlerFunc

RecoveryWithTracing returns a gin.HandlerFunc (middleware) that recovers from any panics and logs requests using uber-go/zap. All errors are logged using zap.Error(). stack means whether output the stack info. The stack info is easy to find where the error occurs but the stack info is too large.

func Register

func Register(middlewares ...gin.HandlerFunc)

Register adds global middlewares that apply to all routes. Must be called before router.Init. Middlewares are auto-wrapped for tracing; name is inferred via reflection.

func RegisterAuth

func RegisterAuth(middlewares ...gin.HandlerFunc)

RegisterAuth adds authentication/authorization middlewares. Must be called before router.Init. Middlewares are auto-wrapped for tracing; name is inferred via reflection.

func RequestSizeLimit added in v0.10.1

func RequestSizeLimit(maxSize int64) gin.HandlerFunc

RequestSizeLimit returns a middleware that limits the size of incoming request bodies. This helps prevent DoS attacks by limiting the amount of data that can be sent in a single request.

Parameters:

  • maxSize: Maximum allowed size in bytes for the request body

Returns:

  • A gin.HandlerFunc that enforces the request size limit

Example:

// Limit request body to 10MB
router.Use(middleware.RequestSizeLimit(10 * 1024 * 1024))

// Limit request body to 1MB
router.Use(middleware.RequestSizeLimit(1024 * 1024))

func RouteParams

func RouteParams() gin.HandlerFunc

RouteParams is a middleware to get route parameters

func SecurityHeaders added in v0.10.1

func SecurityHeaders(config *SecurityHeadersConfig) gin.HandlerFunc

SecurityHeaders returns a middleware that sets security-related HTTP headers. This helps protect against various web vulnerabilities.

Parameters:

  • config: Configuration for security headers. If nil, default secure headers will be used.

Returns:

  • A gin.HandlerFunc that sets security headers

Example:

// Use default secure headers
router.Use(middleware.SecurityHeaders(nil))

// Use custom configuration
router.Use(middleware.SecurityHeaders(&middleware.SecurityHeadersConfig{
	XFrameOptions:            "DENY",
	XContentTypeOptions:      "nosniff",
	XXSSProtection:           "1; mode=block",
	StrictTransportSecurity:  "max-age=31536000; includeSubDomains",
	ContentSecurityPolicy:    "default-src 'self'",
	ReferrerPolicy:           "strict-origin-when-cross-origin",
}))

func Timeout added in v0.10.1

func Timeout(timeout time.Duration) gin.HandlerFunc

Timeout returns a middleware that adds a timeout to the request context. If the request takes longer than the specified duration, it will be canceled.

Parameters:

  • timeout: Maximum duration for the request to complete

Returns:

  • A gin.HandlerFunc that enforces the timeout

Example:

// Set 30 second timeout for all requests
router.Use(middleware.Timeout(30 * time.Second))

// Set 5 second timeout
router.Use(middleware.Timeout(5 * time.Second))

func TraceID

func TraceID() gin.HandlerFunc

func Tracing

func Tracing() gin.HandlerFunc

Tracing returns a middleware that handles both trace ID generation and OpenTelemetry tracing This middleware combines the functionality of TraceID() and Tracing() middlewares

Types

type IPFilterConfig added in v0.10.1

type IPFilterConfig struct {
	// Whitelist contains allowed IP addresses or CIDR ranges
	// If non-empty, only IPs in this list will be allowed
	Whitelist []string

	// Blacklist contains blocked IP addresses or CIDR ranges
	// IPs in this list will always be blocked
	Blacklist []string

	// TrustedProxies contains IP addresses of trusted proxy servers
	// Used to correctly extract the real client IP from X-Forwarded-For header
	TrustedProxies []string
}

IPFilterConfig holds configuration for IP filtering middleware

type SecurityHeadersConfig added in v0.10.1

type SecurityHeadersConfig struct {
	// XFrameOptions controls the X-Frame-Options header
	// Options: "DENY", "SAMEORIGIN", or empty string to disable
	XFrameOptions string

	// XContentTypeOptions controls the X-Content-Type-Options header
	// Set to "nosniff" to enable, or empty string to disable
	XContentTypeOptions string

	// XXSSProtection controls the X-XSS-Protection header
	// Set to "1; mode=block" to enable, or empty string to disable
	XXSSProtection string

	// StrictTransportSecurity controls the Strict-Transport-Security header
	// Set to a value like "max-age=31536000; includeSubDomains" to enable, or empty string to disable
	StrictTransportSecurity string

	// ContentSecurityPolicy controls the Content-Security-Policy header
	// Set to a CSP policy string to enable, or empty string to disable
	ContentSecurityPolicy string

	// ReferrerPolicy controls the Referrer-Policy header
	// Options: "no-referrer", "no-referrer-when-downgrade", "origin", etc., or empty string to disable
	ReferrerPolicy string

	// PermissionsPolicy controls the Permissions-Policy header (formerly Feature-Policy)
	// Set to a permissions policy string to enable, or empty string to disable
	PermissionsPolicy string
}

SecurityHeadersConfig holds configuration for security headers middleware

Jump to

Keyboard shortcuts

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