Help us shape the future of Go! Take the 2026 Go Developer Survey

middleware

package
v0.32.13 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

transport/http/middleware/ - HTTP 中间件

此目录存放 HTTP 全局中间件实现。

现有中间件

  • cors.go - 跨域资源共享配置
  • logger.go - 请求日志记录
  • recovery.go - 异常恢复(防止 panic 导致服务崩溃)

添加新中间件

package middleware

import (
    "context"
    "github.com/cloudwego/hertz/pkg/app"
)

func NewMiddleware() app.HandlerFunc {
    return func(ctx context.Context, c *app.RequestContext) {
        // 前置处理
        c.Next(ctx)
        // 后置处理
    }
}

注册中间件

在 cmd/server/bootstrap/bootstrap.go 中注册:

h.Use(middleware.NewMiddleware())

常用中间件

  • 认证(Auth)
  • 限流(RateLimit)
  • 熔断(CircuitBreaker)
  • 链路追踪(Tracing)
  • 请求 ID(RequestID)

Documentation

Index

Constants

View Source
const (
	// ContextKeyUserID 用户ID上下文键
	ContextKeyUserID = "user_id"
	// ContextKeyUsername 用户名上下文键
	ContextKeyUsername = "username"
	// ContextKeyUserRole 用户角色上下文键
	ContextKeyUserRole = "role"
	// ContextKeyAPIKeyID API Key ID上下文键
	ContextKeyAPIKeyID = "api_key_id"
	// ContextKeyAuthType 认证类型上下文键 (jwt/api_key)
	ContextKeyAuthType = "auth_type"
)
View Source
const (
	// UserRoleAdmin 管理员角色
	UserRoleAdmin = "admin"
	// UserRoleUser 普通用户角色
	UserRoleUser = "user"
)

Variables

This section is empty.

Functions

func GetAPIKeyID

func GetAPIKeyID(c *app.RequestContext) uint

GetAPIKeyID 从上下文获取API Key ID

func GetAuthType

func GetAuthType(c *app.RequestContext) string

GetAuthType 从上下文获取认证类型

func GetUserID

func GetUserID(c *app.RequestContext) uint

GetUserID 从上下文获取用户ID

func GetUserRole

func GetUserRole(c *app.RequestContext) string

GetUserRole 从上下文获取用户角色

func GetUsername

func GetUsername(c *app.RequestContext) string

GetUsername 从上下文获取用户名

func IsAdmin

func IsAdmin(c *app.RequestContext) bool

IsAdmin 检查是否是管理员

func IsAuthenticated

func IsAuthenticated(c *app.RequestContext) bool

IsAuthenticated 检查是否已认证

func RequireAdmin

func RequireAdmin() app.HandlerFunc

RequireAdmin 要求管理员权限的中间件 必须配合 UserAuth 或其他认证中间件使用

func RequireAnyRole

func RequireAnyRole(roles ...string) app.HandlerFunc

RequireAnyRole 要求具备任一指定角色的中间件 必须配合 UserAuth 或其他认证中间件使用

func RequireRole

func RequireRole(role string) app.HandlerFunc

RequireRole 要求特定角色的中间件 必须配合 UserAuth 或其他认证中间件使用

func UserAuth

func UserAuth() app.HandlerFunc

UserAuth 用户 JWT 认证中间件 验证 Bearer JWT token 并将用户信息注入到上下文

Types

This section is empty.

Jump to

Keyboard shortcuts

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