middleware

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2022 License: MIT Imports: 20 Imported by: 1

README

render

gin中间件插件。


安装

go get -u github.com/zhufuyi/pkg/gin/middleware


使用示例

日志中间件

可以设置打印最大长度、添加请求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())

qps限流

path维度的qps限流
    r := gin.Default()

    // path, 默认qps=500, burst=1000
    r.Use(ratelimiter.QPS())

    // path, 自定义qps=50, burst=100
    r.Use(ratelimiter.QPS(
        ratelimiter.WithQPS(50),
        ratelimiter.WithBurst(100),
    ))
ip维度的qps限流
    // ip, 自定义qps=40, burst=80
    r.Use(ratelimiter.QPS(
        ratelimiter.WithIP(),
        ratelimiter.WithQPS(40),
        ratelimiter.WithBurst(80),
    ))

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

This section is empty.

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 Cors

func Cors() gin.HandlerFunc

Cors 跨域

func GetRequestIDFromContext added in v1.3.1

func GetRequestIDFromContext(c *gin.Context) string

GetRequestIDFromContext returns 'RequestID' from the given context if present.

func GetRequestIDFromHeaders added in v1.3.1

func GetRequestIDFromHeaders(c *gin.Context) string

GetRequestIDFromHeaders returns 'RequestID' from the headers if present.

func Logging

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

Logging print request and response info

func RequestID added in v1.3.1

func RequestID() gin.HandlerFunc

RequestID is a middleware 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 middleware that will trace incoming requests. The service parameter should describe the name of the (virtual) server handling the request.

Types

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