Documentation
¶
Overview ¶
Package middleware is gin middleware plugin.
Index ¶
- Constants
- Variables
- func APILogMiddleware(opts ...ApiLogOption) gin.HandlerFunc
- func AdaptCtx(ctx context.Context) (*gin.Context, context.Context)
- func Auth(opts ...JwtOption) gin.HandlerFunc
- func AuthCustom(verify VerifyCustomFn, opts ...JwtOption) gin.HandlerFunc
- func CircuitBreaker(opts ...CircuitBreakerOption) gin.HandlerFunc
- func Cors(opts ...CorsOption) gin.HandlerFunc
- func CtxRequestID(ctx context.Context) string
- func CtxRequestIDField(ctx context.Context) zap.Field
- func GCtxRequestID(c *gin.Context) string
- func GCtxRequestIDField(c *gin.Context) zap.Field
- func GetFromCtx(ctx context.Context, key string) interface{}
- func GetFromHeader(ctx context.Context, key string) string
- func GetFromHeaders(ctx context.Context, key string) []string
- func HeaderRequestID(c *gin.Context) string
- func HeaderRequestIDField(c *gin.Context) zap.Field
- func IPWhiteListMiddleware(opts ...WhiteListOption) gin.HandlerFunc
- func Logging(opts ...Option) gin.HandlerFunc
- func RateLimit(opts ...RateLimitOption) gin.HandlerFunc
- func RequestID(opts ...RequestIDOption) gin.HandlerFunc
- func SentinelMiddleware(opts ...SentinelOptions) gin.HandlerFunc
- func Timeout(d time.Duration) gin.HandlerFunc
- func Tracing(serviceName string, opts ...TraceOption) gin.HandlerFunc
- func VerifySignatureMiddleware(opts ...SignOption) gin.HandlerFunc
- func WrapCtx(c *gin.Context) context.Context
- func XSSCrossMiddleware(opts ...XssOptions) gin.HandlerFunc
- type ApiLogFunc
- type ApiLogOption
- type ApiLogOptions
- type ApiLogRecord
- type CircuitBreakerOption
- type CorsConfig
- type CorsOption
- func WithAllowCredentials(allow bool) CorsOption
- func WithAllowHeaders(headers []string) CorsOption
- func WithAllowMethods(methods []string) CorsOption
- func WithAllowOrigins(origins []string) CorsOption
- func WithExposeHeaders(headers []string) CorsOption
- func WithMaxAge(maxAge time.Duration) CorsOption
- func WithXFrameOptions(xFrameOptions string) CorsOption
- type CtxKeyString
- type JwtOption
- type Option
- func WithIgnoreRoutes(routes ...string) Option
- func WithLog(log *zap.Logger) Option
- func WithLogFrom(logFrom string) Option
- func WithLogHeaders() Option
- func WithMaxLen(maxLen int) Option
- func WithRequestIDFromContext() Option
- func WithRequestIDFromHeader() Option
- func WithSensitiveHeaders(headers ...string) Option
- type RateLimitOption
- type RequestIDOption
- type ResponseWriter
- type SentinelOptions
- type SignOption
- type TraceOption
- type VerifyCustomFn
- type VerifyFn
- type WhiteListOption
- type XssOptions
Constants ¶
const (
// HeaderAuthorizationKey http header authorization key
HeaderAuthorizationKey = "Authorization"
)
Variables ¶
var ( // ContextRequestIDKey request id for context ContextRequestIDKey = "request_id" // HeaderXRequestIDKey header request id key HeaderXRequestIDKey = "X-Request-Id" )
var ErrLimitExceed = rl.ErrLimitExceed
ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.
var ErrNotAllowed = circuitbreaker.ErrNotAllowed
ErrNotAllowed error not allowed.
var RequestHeaderKey = "request_header_key"
RequestHeaderKey request header key
var RequestIDKey = CtxKeyString(ContextRequestIDKey)
RequestIDKey request_id
Functions ¶
func APILogMiddleware ¶ added in v1.4.3
func APILogMiddleware(opts ...ApiLogOption) gin.HandlerFunc
APILogMiddleware 记录API请求日志的中间件 * 使用案例 // 对象池用于重用CpDealerApiLog实例
var cpDealerApiLogPool = sync.Pool{
New: func() interface{} {
return &model.CpDealerApiLog{}
},
}
func customLogFunc(c *gin.Context, reqBody []byte, respBody []byte, startTime time.Time, endTime time.Time, spendTime int64) {
go func() {
// 从池中获取CpDealerApiLog实例
log := cpDealerApiLogPool.Get().(*model.CpDealerApiLog)
// 重置字段值
log.Type = "接口"
log.Category = "API"
log.IP = c.ClientIP()
log.Url = c.Request.URL.String()
log.Params = string(reqBody)
log.Response = string(respBody)
log.StartTime = cast.ToString(startTime.UnixMilli())
log.EndTime = cast.ToString(endTime.UnixMilli())
log.SpendTime = cast.ToString(spendTime)
log.DealerID = c.GetInt("uid")
log.Active = "golang api"
log.CreateTime = cast.ToString(time.Now().Unix())
log.UpdateTime = int(time.Now().Unix())
// 保存到数据库
database.GetDB().Create(log)
// 使用完毕后将对象放回池中
cpDealerApiLogPool.Put(log)
}()
}
r.Use(APILogMiddleware(WithApiLogFunc(customLogFunc)))
func AdaptCtx ¶
AdaptCtx adapt context, if ctx is gin.Context, return gin.Context and context of the transformation
func AuthCustom ¶
func AuthCustom(verify VerifyCustomFn, opts ...JwtOption) gin.HandlerFunc
AuthCustom custom authentication
func CircuitBreaker ¶
func CircuitBreaker(opts ...CircuitBreakerOption) gin.HandlerFunc
CircuitBreaker a circuit breaker middleware
func Cors ¶
func Cors(opts ...CorsOption) gin.HandlerFunc
Cors creates a new CORS middleware with options.
func CtxRequestID ¶
CtxRequestID get request id from context.Context
func CtxRequestIDField ¶
CtxRequestIDField get request id field from context.Context
func GCtxRequestID ¶
GCtxRequestID get request id from gin.Context
func GCtxRequestIDField ¶
GCtxRequestIDField get request id field from gin.Context
func GetFromCtx ¶
GetFromCtx get value from context
func GetFromHeader ¶
GetFromHeader get value from header
func GetFromHeaders ¶
GetFromHeaders get values from header
func HeaderRequestID ¶
HeaderRequestID get request id from the header
func HeaderRequestIDField ¶
HeaderRequestIDField get request id field from header
func IPWhiteListMiddleware ¶ added in v1.3.39
func IPWhiteListMiddleware(opts ...WhiteListOption) gin.HandlerFunc
IPWhiteListMiddleware IP白名单中间件
func RateLimit ¶
func RateLimit(opts ...RateLimitOption) gin.HandlerFunc
RateLimit an adaptive rate limiter middleware
func RequestID ¶
func RequestID(opts ...RequestIDOption) gin.HandlerFunc
RequestID is an interceptor that injects a 'request id' into the context and request/response header of each request.
func SentinelMiddleware ¶ added in v1.3.4
func SentinelMiddleware(opts ...SentinelOptions) gin.HandlerFunc
SentinelMiddleware 返回一个 Gin 中间件,用于限流控制
func Tracing ¶
func Tracing(serviceName string, opts ...TraceOption) gin.HandlerFunc
Tracing returns interceptor that will trace incoming requests. The service parameter should describe the name of the (virtual) server handling the request.
func VerifySignatureMiddleware ¶ added in v1.0.2
func VerifySignatureMiddleware(opts ...SignOption) gin.HandlerFunc
func XSSCrossMiddleware ¶ added in v1.0.2
func XSSCrossMiddleware(opts ...XssOptions) gin.HandlerFunc
Types ¶
type ApiLogFunc ¶ added in v1.4.3
type ApiLogFunc func(c *gin.Context, reqBody []byte, respBody []byte, startTime time.Time, endTime time.Time, spendTime int64)
ApiLogFunc 定义记录API日志的函数类型
type ApiLogOption ¶ added in v1.4.3
type ApiLogOption func(*ApiLogOptions)
ApiLogOption API日志中间件配置函数类型
func WithApiLogFunc ¶ added in v1.4.3
func WithApiLogFunc(logFunc ApiLogFunc) ApiLogOption
WithApiLogFunc 设置自定义日志记录函数
type ApiLogOptions ¶ added in v1.4.3
type ApiLogOptions struct {
LogFunc ApiLogFunc
}
ApiLogOptions API日志中间件配置选项
type CircuitBreakerOption ¶
type CircuitBreakerOption func(*circuitBreakerOptions)
CircuitBreakerOption set the circuit breaker circuitBreakerOptions.
func WithDegradeHandler ¶
func WithDegradeHandler(handler func(c *gin.Context)) CircuitBreakerOption
WithDegradeHandler set degrade handler function
func WithGroup ¶
func WithGroup(g *group.Group) CircuitBreakerOption
WithGroup with circuit breaker group. NOTE: implements generics circuitbreaker.CircuitBreaker
func WithValidCode ¶
func WithValidCode(code ...int) CircuitBreakerOption
WithValidCode http code to mark failed
type CorsConfig ¶ added in v1.1.77
type CorsConfig struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge time.Duration
XFrameOptions string // 新增字段
}
CorsConfig holds the configuration for CORS middleware
type CorsOption ¶ added in v1.1.77
type CorsOption func(*CorsConfig)
CorsOption set the CORS options.
func WithAllowCredentials ¶ added in v1.1.77
func WithAllowCredentials(allow bool) CorsOption
WithAllowCredentials sets whether to allow credentials.
func WithAllowHeaders ¶ added in v1.1.77
func WithAllowHeaders(headers []string) CorsOption
WithAllowHeaders sets the allowed headers.
func WithAllowMethods ¶ added in v1.1.77
func WithAllowMethods(methods []string) CorsOption
WithAllowMethods sets the allowed methods.
func WithAllowOrigins ¶ added in v1.1.77
func WithAllowOrigins(origins []string) CorsOption
WithAllowOrigins sets the allowed origins.
func WithExposeHeaders ¶ added in v1.1.77
func WithExposeHeaders(headers []string) CorsOption
WithExposeHeaders sets the exposed headers.
func WithMaxAge ¶ added in v1.1.77
func WithMaxAge(maxAge time.Duration) CorsOption
WithMaxAge sets the max age.
func WithXFrameOptions ¶ added in v1.1.82
func WithXFrameOptions(xFrameOptions string) CorsOption
WithXFrameOptions sets the X-Frame-Options header.
type JwtOption ¶
type JwtOption func(*jwtOptions)
JwtOption set the jwt options.
func WithAuthUidFields ¶ added in v1.4.1
WithAuthUidFields 设置用户ID字段名列表,按优先级排序
func WithJwtIgnoreMethods ¶ added in v1.1.67
WithJwtIgnoreMethods 设置忽略jwt的方法 fullMethodName 格式: /packageName.serviceName/methodName, 示例 /api.userExample.v1.userExampleService/GetByID
func WithSwitchHTTPCode ¶
func WithSwitchHTTPCode() JwtOption
WithSwitchHTTPCode switch to http code
type Option ¶
type Option func(*options)
Option set the gin logger options.
func WithIgnoreRoutes ¶
WithIgnoreRoutes no logger content routes
func WithLogFrom ¶ added in v1.0.2
func WithLogHeaders ¶ added in v1.3.12
func WithLogHeaders() Option
WithLogHeaders enable logging request headers
func WithRequestIDFromContext ¶
func WithRequestIDFromContext() Option
WithRequestIDFromContext name is field in context, default value is request_id
func WithRequestIDFromHeader ¶
func WithRequestIDFromHeader() Option
WithRequestIDFromHeader name is field in header, default value is X-Request-Id
func WithSensitiveHeaders ¶ added in v1.3.12
WithSensitiveHeaders set sensitive headers that should not be logged
type RateLimitOption ¶
type RateLimitOption func(*rateLimitOptions)
RateLimitOption set the rate limits rateLimitOptions.
func WithCPUQuota ¶
func WithCPUQuota(quota float64) RateLimitOption
WithCPUQuota with real cpu quota(if it can not collect from process correct);
func WithCPUThreshold ¶
func WithCPUThreshold(threshold int64) RateLimitOption
WithCPUThreshold with cpu threshold
type RequestIDOption ¶
type RequestIDOption func(*requestIDOptions)
RequestIDOption set the request id options.
func WithContextRequestIDKey ¶
func WithContextRequestIDKey(key string) RequestIDOption
WithContextRequestIDKey set context request id key, minimum length of 4
func WithHeaderRequestIDKey ¶
func WithHeaderRequestIDKey(key string) RequestIDOption
WithHeaderRequestIDKey set header request id key, minimum length of 4
func WithSnow ¶ added in v1.0.39
func WithSnow(snow *snowflake.Node) RequestIDOption
type ResponseWriter ¶ added in v1.4.3
type ResponseWriter struct {
gin.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter 自定义响应writer,用于捕获响应体
type SentinelOptions ¶ added in v1.3.4
type SentinelOptions func(*sentinelOptions)
SentinelOptions set the gin logger options.
func WithSentinelLog ¶ added in v1.3.4
func WithSentinelLog(log *zap.Logger) SentinelOptions
WithSentinelLog set log
func WithSentinelResourceExtractor ¶ added in v1.3.5
func WithSentinelResourceExtractor(fn func(*gin.Context) string) SentinelOptions
WithSentinelResourceExtractor 设置资源提取器
func WithSentinelRules ¶ added in v1.3.5
func WithSentinelRules(ruleInfos any) SentinelOptions
WithSentinelRules set rules
type SignOption ¶ added in v1.1.54
type SignOption func(*signOptions)
func WithIgnoreUrl ¶ added in v1.1.54
func WithIgnoreUrl(urls ...string) SignOption
func WithSignExpiredTime ¶ added in v1.1.56
func WithSignExpiredTime(signExpiredTime time.Duration) SignOption
func WithSignKey ¶ added in v1.1.54
func WithSignKey(signKey string) SignOption
func WithSignLog ¶ added in v1.3.12
func WithSignLog(log *zap.Logger) SignOption
WithSignLog set log
type TraceOption ¶
type TraceOption func(*traceConfig)
TraceOption specifies instrumentation configuration options.
func WithPropagators ¶
func WithPropagators(propagators propagation.TextMapPropagator) TraceOption
WithPropagators specifies propagators to use for extracting information from the HTTP requests. If none are specified, global ones will be used.
func WithTracerProvider ¶
func WithTracerProvider(provider oteltrace.TracerProvider) TraceOption
WithTracerProvider specifies a tracer provider to use for creating a tracer. If none is specified, the global provider is used.
type VerifyCustomFn ¶
VerifyCustomFn verify custom function, tokenTail10 is the last 10 characters of the token.
type WhiteListOption ¶ added in v1.3.39
type WhiteListOption func(*whiteListOptions)
func WithWhiteListIP ¶ added in v1.3.39
func WithWhiteListIP(ips ...string) WhiteListOption
WithWhiteListIP 设置白名单IP
func WithWhiteListLog ¶ added in v1.3.39
func WithWhiteListLog(log *zap.Logger) WhiteListOption
WithWhiteListLog set log
type XssOptions ¶ added in v1.1.77
type XssOptions func(*xssOptions)
func WithIgnoreXssUrl ¶ added in v1.1.77
func WithIgnoreXssUrl(urls ...string) XssOptions
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package metrics is gin metrics library, collect five metrics, "uptime", "http_request_count_total", "http_request_duration_seconds", "http_request_size_bytes", "http_response_size_bytes".
|
Package metrics is gin metrics library, collect five metrics, "uptime", "http_request_count_total", "http_request_duration_seconds", "http_request_size_bytes", "http_response_size_bytes". |