middleware

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 24 Imported by: 1

README

middleware

gin中间件插件。


使用示例

日志中间件

可以设置打印最大长度、添加请求id字段、忽略打印path、自定义zap log

    r := gin.Default()

    // 默认打印日志
    r.Use(middleware.Logging())

    // 自定义打印日志
    r.Use(middleware.Logging(
        middleware.WithMaxLen(400), // 打印body最大长度,超过则忽略
		//WithRequestIDFromHeader(), // 支持自定义requestID名称
		WithRequestIDFromContext(), // 支持自定义requestID名称
        //middleware.WithIgnoreRoutes("/hello"), // 忽略/hello
    ))

    // 自定义zap log
    log, _ := logger.Init(logger.WithFormat("json"))
    r.Use(middlewareLogging(
        middleware.WithLog(log),
    ))

允许跨域请求

    r := gin.Default()
    r.Use(middleware.Cors())

限流

方式一:根据硬件资源自适应限流
	r := gin.Default()

    // e.g. (1) use default
    // r.Use(RateLimit())
    
    // e.g. (2) custom parameters
    r.Use(RateLimit(
    WithWindow(time.Second*10),
    WithBucket(100),
    WithCPUThreshold(100),
    WithCPUQuota(0.5),
    ))

熔断器

    r := gin.Default()
    r.Use(CircuitBreaker())

jwt鉴权

    r := gin.Default()
    r.GET("/user/:id", middleware.JWT(), userFun) // 需要鉴权

链路跟踪

// 初始化trace
func InitTrace(serviceName string) {
	exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
	if err != nil {
		panic(err)
	}

	resource := tracer.NewResource(
		tracer.WithServiceName(serviceName),
		tracer.WithEnvironment("dev"),
		tracer.WithServiceVersion("demo"),
	)

	tracer.Init(exporter, resource) // 默认采集全部
}

func NewRouter(
    r := gin.Default()
    r.Use(middleware.Tracing("your-service-name"))

    // ......
)

// 如果有需要,可以在程序创建一个span
func SpanDemo(serviceName string, spanName string, ctx context.Context) {
	_, span := otel.Tracer(serviceName).Start(
		ctx, spanName,
		trace.WithAttributes(attribute.String(spanName, time.Now().String())), // 自定义属性
	)
	defer span.End()

	// ......
}

监控指标

	r := gin.Default()

	r.Use(metrics.Metrics(r,
		//metrics.WithMetricsPath("/demo/metrics"), // default is /metrics
		metrics.WithIgnoreStatusCodes(http.StatusNotFound), // ignore status codes
		//metrics.WithIgnoreRequestMethods(http.MethodHead),  // ignore request methods
		//metrics.WithIgnoreRequestPaths("/ping", "/health"), // ignore request paths
	))

Documentation

Index

Constants

View Source
const (
	// ContextRequestIDKey context request id for context
	ContextRequestIDKey = "request_id"

	// HeaderXRequestIDKey http header request id key
	HeaderXRequestIDKey = "X-Request-ID"
)

Variables

View Source
var ErrLimitExceed = rl.ErrLimitExceed

ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.

ErrNotAllowed error not allowed.

Functions

func Auth added in v1.3.0

func Auth() gin.HandlerFunc

Auth 鉴权

func AuthAdmin added in v1.3.0

func AuthAdmin() gin.HandlerFunc

AuthAdmin 管理员鉴权

func CircuitBreaker added in v1.4.0

func CircuitBreaker(opts ...CircuitBreakerOption) gin.HandlerFunc

CircuitBreaker a circuit breaker middleware

func Cors

func Cors() gin.HandlerFunc

Cors 跨域

func CtxRequestID added in v1.4.0

func CtxRequestID(ctx context.Context) string

CtxRequestID get request id from context.Context

func CtxRequestIDField added in v1.4.0

func CtxRequestIDField(ctx context.Context) zap.Field

CtxRequestIDField get request id field from context.Context

func GCtxRequestID added in v1.4.0

func GCtxRequestID(c *gin.Context) string

GCtxRequestID get request id from gin.Context

func GCtxRequestIDField added in v1.4.0

func GCtxRequestIDField(c *gin.Context) zap.Field

GCtxRequestIDField get request id field from gin.Context

func HeaderRequestID added in v1.4.0

func HeaderRequestID(c *gin.Context) string

HeaderRequestID get request id from the header

func HeaderRequestIDField added in v1.4.0

func HeaderRequestIDField(c *gin.Context) zap.Field

HeaderRequestIDField get request id field from header

func Logging

func Logging(opts ...Option) gin.HandlerFunc

Logging print request and response info

func RateLimit added in v1.4.0

func RateLimit(opts ...RateLimitOption) gin.HandlerFunc

RateLimit an adaptive rate limiter middleware

func RequestID added in v1.3.1

func RequestID() gin.HandlerFunc

RequestID is an interceptor that injects a 'X-Request-ID' into the context and request/response header of each request.

func Tracing added in v1.3.0

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.

Types

type CircuitBreakerOption added in v1.4.0

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption set the circuit breaker circuitBreakerOptions.

func WithGroup added in v1.4.0

func WithGroup(g *group.Group) CircuitBreakerOption

WithGroup with circuit breaker group. NOTE: implements generics circuitbreaker.CircuitBreaker

type Option

type Option func(*options)

Option set the gin logger options.

func WithIgnoreRoutes

func WithIgnoreRoutes(routes ...string) Option

WithIgnoreRoutes no logger content routes

func WithLog

func WithLog(log *zap.Logger) Option

WithLog set log

func WithMaxLen

func WithMaxLen(maxLen int) Option

WithMaxLen logger content max length

func WithRequestIDFromContext added in v1.3.2

func WithRequestIDFromContext(name ...string) Option

WithRequestIDFromContext name is field in context, default value is request_id

func WithRequestIDFromHeader added in v1.3.2

func WithRequestIDFromHeader(name ...string) Option

WithRequestIDFromHeader name is field in header, default value is X-Request-Id

type RateLimitOption added in v1.4.0

type RateLimitOption func(*rateLimitOptions)

RateLimitOption set the rate limits rateLimitOptions.

func WithBucket added in v1.4.0

func WithBucket(b int) RateLimitOption

WithBucket with bucket size.

func WithCPUQuota added in v1.4.0

func WithCPUQuota(quota float64) RateLimitOption

WithCPUQuota with real cpu quota(if it can not collect from process correct);

func WithCPUThreshold added in v1.4.0

func WithCPUThreshold(threshold int64) RateLimitOption

WithCPUThreshold with cpu threshold

func WithWindow added in v1.4.0

func WithWindow(d time.Duration) RateLimitOption

WithWindow with window size.

type TraceOption added in v1.3.1

type TraceOption func(*traceConfig)

TraceOption specifies instrumentation configuration options.

func WithPropagators added in v1.3.0

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 added in v1.3.0

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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