mid

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package mid provides common Gin middleware: panic recovery, CORS, JWT authentication, rate limiting, traceId, and gRPC interceptors.

Index

Constants

View Source
const TraceHeader = "X-Trace-Id"

Variables

This section is empty.

Functions

func CORS

func CORS(allowOrigins ...string) gin.HandlerFunc

CORS returns a CORS middleware. Pass no args for allow-all, or pass allowed origins for whitelist mode.

func CORSFromConfig added in v0.3.0

func CORSFromConfig(cfg CORSCfg) gin.HandlerFunc

CORSFromConfig creates CORS middleware from CORSConfig.

func Default added in v0.3.0

func Default(r *gin.Engine, cfg DefaultConfig)

Default registers all standard middleware on the Gin engine. Order: Trace → Recovery → ErrorHandler → Logger → CORS → RateLimit

Usage:

mid.Default(a.Gin, mid.DefaultConfig{
    CORS: mid.CORSCfg{Enable: true, Mode: "allow-all"},
    AccessLimit: mid.AccessLimitCfg{Enable: true, Total: 300, Duration: 5},
})

func ErrorHandler added in v0.3.0

func ErrorHandler() gin.HandlerFunc

ErrorHandler returns a middleware that catches panics and converts them to proper JSON responses. It handles:

  • *AppError → resp.Fail with the error's code and message
  • "CustomError#code#msg" strings (legacy dilu format)
  • Other panics → 500 internal error

func GRPCStreamClientInterceptor added in v0.2.0

func GRPCStreamClientInterceptor() grpc.StreamClientInterceptor

GRPCStreamClientInterceptor injects trace_id for outgoing stream calls.

func GRPCStreamServerInterceptor added in v0.2.0

func GRPCStreamServerInterceptor() grpc.StreamServerInterceptor

GRPCStreamServerInterceptor extracts trace_id for incoming stream calls.

func GRPCUnaryClientInterceptor added in v0.2.0

func GRPCUnaryClientInterceptor() grpc.UnaryClientInterceptor

GRPCUnaryClientInterceptor injects trace_id from context into gRPC metadata for outgoing unary calls. Use when dialing another service.

conn, _ := grpc.NewClient(addr, grpc.WithUnaryInterceptor(mid.GRPCUnaryClientInterceptor()))

func GRPCUnaryServerInterceptor added in v0.2.0

func GRPCUnaryServerInterceptor() grpc.UnaryServerInterceptor

GRPCUnaryServerInterceptor extracts trace_id from incoming gRPC metadata and stores it in the context. Use when registering a gRPC server.

grpc.NewServer(grpc.UnaryInterceptor(mid.GRPCUnaryServerInterceptor()))

func GetNickname added in v0.3.0

func GetNickname(c *gin.Context) string

GetNickname extracts the nickname from the Gin context.

func GetPhone added in v0.3.0

func GetPhone(c *gin.Context) string

GetPhone extracts the phone from the Gin context.

func GetRoleID added in v0.3.0

func GetRoleID(c *gin.Context) int

GetRoleID extracts the role ID from the Gin context.

func GetTraceID added in v0.2.0

func GetTraceID(c *gin.Context) string

GetTraceID extracts the trace ID from a Gin context.

func GetUID

func GetUID(c *gin.Context) int64

GetUID extracts the authenticated user ID from the Gin context.

func JWT

func JWT(cfg JWTConfig) gin.HandlerFunc

JWT returns a Gin middleware that verifies Bearer tokens. On success it sets "uid" (int64) in the Gin context.

func Logger added in v0.3.0

func Logger() gin.HandlerFunc

Logger returns a Gin middleware that logs every request with method, path, status, latency, client IP, and trace_id.

func PanicApp added in v0.3.0

func PanicApp(code int, msg string)

PanicApp panics with an AppError, to be caught by ErrorHandler.

func RateLimit

func RateLimit(max int, window time.Duration) gin.HandlerFunc

RateLimit returns a simple in-memory rate limiter middleware. max requests per window per client IP.

func Recovery

func Recovery() gin.HandlerFunc

Recovery returns a middleware that recovers from panics and returns a 500.

func Trace added in v0.2.0

func Trace() gin.HandlerFunc

Trace returns a Gin middleware that extracts or generates a trace ID, stores it in the context, and sets the response header.

Types

type AccessLimitCfg added in v0.3.0

type AccessLimitCfg struct {
	Enable   bool
	Total    int // max requests per window (default 300)
	Duration int // window in seconds (default 5)
}

AccessLimitCfg for rate limiting.

type AppError added in v0.3.0

type AppError struct {
	Code int
	Msg  string
}

AppError is a typed error that can be caught by the ErrorHandler middleware.

func NewAppError added in v0.3.0

func NewAppError(code int, msg string) *AppError

NewAppError creates an AppError for panic-based error handling.

func (*AppError) Error added in v0.3.0

func (e *AppError) Error() string

type CORSCfg added in v0.3.0

type CORSCfg struct {
	Enable    bool
	Mode      string
	Whitelist []string
}

CORSCfg mirrors boot.CORSConfig for mid package use (avoids circular import).

type DefaultConfig added in v0.3.0

type DefaultConfig struct {
	CORS        CORSCfg
	AccessLimit AccessLimitCfg
}

DefaultConfig holds settings for the Default middleware chain. Map this from your boot.Config in main.go.

type JWTConfig

type JWTConfig struct {
	Secret string // HMAC signing key

	// HeaderUID is an optional header name for pre-verified user ID
	// (e.g. from an API gateway). If set and present, JWT parsing is skipped.
	HeaderUID string // default: "" (disabled)
}

JWTConfig configures the JWT middleware.

Jump to

Keyboard shortcuts

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