middleware

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2023 License: MIT Imports: 24 Imported by: 0

README

middleware

gin middleware plugin.


Example of use

logging middleware

You can set the maximum length for printing, add a request id field, ignore print path, customize zap log

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

    r.Use(middleware.Logging(
        middleware.WithMaxLen(400),
		//WithRequestIDFromHeader(),
		WithRequestIDFromContext(),
        //middleware.WithIgnoreRoutes("/hello"),
    ))

    log, _ := logger.Init(logger.WithFormat("json"))
    r.Use(middlewareLogging(
        middleware.WithLog(log),
    ))

Allow cross-domain requests middleware

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

rate limiter middleware

Adaptive flow limitation based on hardware resources.

	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),
    ))

Circuit Breaker middleware

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

jwt authorization middleware

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

tracing middleware

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) // collect all by default
}

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

    // ......
)

// if necessary, you can create a span in the program
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()

	// ......
}

Metrics middleware

	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
	))

Request id

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

Documentation

Overview

Package middleware is gin middleware plugin.

Index

Constants

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

	// HeaderXRequestIDKey http header request id key
	HeaderXRequestIDKey = "X-Request-ID"
)
View Source
const (
	// HeaderAuthorizationKey http header authorization key
	HeaderAuthorizationKey = "Authorization"
)

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.

RequestIDKey "request_id"

Functions

func Auth

func Auth() gin.HandlerFunc

Auth authorization

func AuthAdmin

func AuthAdmin() gin.HandlerFunc

AuthAdmin admin authentication

func CircuitBreaker

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

CircuitBreaker a circuit breaker middleware

func Cors

func Cors() gin.HandlerFunc

Cors cross domain

func CtxRequestID

func CtxRequestID(ctx context.Context) string

CtxRequestID get request id from context.Context

func CtxRequestIDField

func CtxRequestIDField(ctx context.Context) zap.Field

CtxRequestIDField get request id field from context.Context

func GCtxRequestID

func GCtxRequestID(c *gin.Context) string

GCtxRequestID get request id from gin.Context

func GCtxRequestIDField

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

GCtxRequestIDField get request id field from gin.Context

func HeaderRequestID

func HeaderRequestID(c *gin.Context) string

HeaderRequestID get request id from the header

func HeaderRequestIDField

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

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

RateLimit an adaptive rate limiter middleware

func RequestID

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

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

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption set the circuit breaker circuitBreakerOptions.

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 CtxKeyString

type CtxKeyString string

CtxKeyString for context.WithValue key type

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

func WithRequestIDFromContext(name ...string) Option

WithRequestIDFromContext name is field in context, default value is request_id

func WithRequestIDFromHeader

func WithRequestIDFromHeader(name ...string) Option

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

type RateLimitOption

type RateLimitOption func(*rateLimitOptions)

RateLimitOption set the rate limits rateLimitOptions.

func WithBucket

func WithBucket(b int) RateLimitOption

WithBucket with bucket size.

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

func WithWindow

func WithWindow(d time.Duration) RateLimitOption

WithWindow with window size.

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.

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".

Jump to

Keyboard shortcuts

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