webapp

package
v0.0.0-...-93285d4 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2025 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

Package webapp 是一个轻量级的 Go Web 应用开发模板。 基于 Gin/Echo 框架,并结合了一些常用的开源库,如:GORM、Viper、Zap 等, 提供依赖注入、鉴权授权、Swagger 文档生成、配置管理、中间件支持等功能。 适用于快速构建 RESTful API 和 Web 服务。

webapp/router_options.go

Index

Constants

View Source
const (
	Actor                      = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"
	PostalCode                 = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"
	PrimaryGroupSid            = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid"
	PrimarySid                 = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid"
	Role                       = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
	Rsa                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"
	SerialNumber               = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber"
	Sid                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid"
	Spn                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn"
	StateOrProvince            = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"
	StreetAddress              = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"
	Surname                    = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"
	System                     = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system"
	Thumbprint                 = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint"
	Upn                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
	Uri                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri"
	UserData                   = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata"
	Version                    = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version"
	Webpage                    = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage"
	WindowsAccountName         = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"
	WindowsDeviceClaim         = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim"
	WindowsDeviceGroup         = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup"
	WindowsFqbnVersion         = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion"
	WindowsSubAuthority        = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority"
	OtherPhone                 = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone"
	NameIdentifier             = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
	Name                       = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
	MobilePhone                = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone"
	Anonymous                  = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous"
	Authentication             = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authenticated"
	AuthenticationInstant      = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant"
	AuthenticationMethod       = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"
	AuthorizationDecision      = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision"
	CookiePath                 = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath"
	Country                    = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"
	DateOfBirth                = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"
	DenyOnlyPrimaryGroupSid    = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid"
	DenyOnlyPrimarySid         = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid"
	DenyOnlySid                = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid"
	WindowsUserClaim           = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim"
	DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup"
	Dsa                        = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa"
	Email                      = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
	Expiration                 = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration"
	Expired                    = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired"
	Gender                     = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"
	GivenName                  = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
	GroupSid                   = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid"
	Hash                       = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash"
	HomePhone                  = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone"
	IsPersistent               = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent"
	Locality                   = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"
	Dns                        = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns"
	X500DistinguishedName      = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname"
)
View Source
const SchemeJwtBearer = "JwtBearer"

Variables

ANY is a slice of all HTTP request methods

Functions

func JoinPaths

func JoinPaths(paths ...string) string

JoinPaths 拼接多个 URL path 段,自动处理斜杠问题。 例如:

JoinPaths("/api", "v1", "users")      => "/api/v1/users"
JoinPaths("/api/", "/v1/", "/users/") => "/api/v1/users/"
JoinPaths("/", "/")                   => "/"

func NewGrpcServer

func NewGrpcServer(lc fx.Lifecycle, logger *zap.Logger, opt ServerOptions) *grpc.Server

NewGrpcServer 启动 gRPC 服务

Types

type AESDataProtector

type AESDataProtector struct {
	// contains filtered or unexported fields
}

AESDataProtector 使用 AES 加密实现数据保护

func (*AESDataProtector) Protect

func (p *AESDataProtector) Protect(data []byte) ([]byte, error)

Protect 加密数据

func (*AESDataProtector) Unprotect

func (p *AESDataProtector) Unprotect(protectedData []byte) ([]byte, error)

Unprotect 解密数据

type AuthProperties

type AuthProperties struct {
	IssuedUtc    time.Time `json:"issuedUtc"`
	ExpiresUtc   time.Time `json:"expiresUtc"`
	IsPersistent bool      `json:"isPersistent"`
	RedirectUri  string    `json:"redirectUri,omitempty"`
}

AuthProperties 认证属性

type AuthenticateProvider

type AuthenticateProvider struct {
	// contains filtered or unexported fields
}

AuthenticateProvider 鉴权提供者

type AuthenticationBuilder

type AuthenticationBuilder struct {
	// contains filtered or unexported fields
}

AuthenticationBuilder 鉴权构建器

func (*AuthenticationBuilder) AddCookie

func (b *AuthenticationBuilder) AddCookie(schemeName string, fn func(*CookieOptions)) *AuthenticationBuilder

AddCookie 注册新的 schemename Cookie鉴权方案

func (*AuthenticationBuilder) AddJwtBearer

func (b *AuthenticationBuilder) AddJwtBearer(schemeName string, fn func(*JwtBearerOptions)) *AuthenticationBuilder

AddJwtBearer 注册新的 schemename JWT Bearer鉴权方案

func (*AuthenticationBuilder) AddScheme

func (b *AuthenticationBuilder) AddScheme(schemeName string, handler AuthenticationHandler) *AuthenticationBuilder

AddScheme 注册新的鉴权方案

func (*AuthenticationBuilder) Build

Build 构建鉴权提供者

func (*AuthenticationBuilder) Schemes

Schemes 返回所有注册的鉴权方案

type AuthenticationHandler

type AuthenticationHandler interface {
	Scheme() string
	Authenticate(r *http.Request) (*ClaimsPrincipal, error)
}

AuthenticationHandler is an interface for handling authentication.

type AuthenticationOptions

type AuthenticationOptions struct {
	DefaultScheme string

	*AuthenticationBuilder
	// contains filtered or unexported fields
}

AuthenticationOptions 表示授权选项配置。

type AuthenticationTicket

type AuthenticationTicket struct {
	ClaimsPrincipal ClaimsPrincipal `json:"claimsPrincipal"`
	Properties      AuthProperties  `json:"properties"`
}

AuthenticationTicket 认证票据,包含用户声明和认证属性

type AuthorizationBuilder

type AuthorizationBuilder struct {
	// contains filtered or unexported fields
}

AuthorizationBuilder 用于构建授权策略

func (*AuthorizationBuilder) AddPolicy

func (ab *AuthorizationBuilder) AddPolicy(policyName string, policy func(claims *ClaimsPrincipal) bool) *AuthorizationBuilder

AddPolicy 添加一个策略

func (*AuthorizationBuilder) Build

Build 构建授权提供者

func (*AuthorizationBuilder) Policies

func (ab *AuthorizationBuilder) Policies(policyName ...string) map[string]func(claims *ClaimsPrincipal) bool

Policies 根据名称获取策略, 如果没有指定名称则返回全部策略

func (*AuthorizationBuilder) Policy

func (ab *AuthorizationBuilder) Policy(policyName string) func(claims *ClaimsPrincipal) bool

Policy 根据名称返回单个策略

func (*AuthorizationBuilder) RequireClaim

func (ab *AuthorizationBuilder) RequireClaim(policyName, k string, v interface{}) *AuthorizationBuilder

RequireClaimPolicy 添加一个要求指定 claim 的策略

func (*AuthorizationBuilder) RequireHasChaims

func (ab *AuthorizationBuilder) RequireHasChaims(policyName, k string) *AuthorizationBuilder

RequireHasChaimsPolicy 添加一个要求指定 claim 的策略

func (*AuthorizationBuilder) RequireRole

func (ab *AuthorizationBuilder) RequireRole(policyName string, role ...string) *AuthorizationBuilder

RequireRolePolicy 添加一个要求指定角色的策略

type AuthorizationOptions

type AuthorizationOptions struct {
	DefaultPolicy string

	*AuthorizationBuilder
	// contains filtered or unexported fields
}

AuthorizationOptions 表示授权选项配置

type AuthorizationProvider

type AuthorizationProvider struct {
	// contains filtered or unexported fields
}

AuthorizationProvider is the interface for authorization providers.

type BackgroundService

type BackgroundService interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

BackgroundService 定义后台任务标准接口

type CacheContextOptions

type CacheContextOptions struct {
	// contains filtered or unexported fields
}

func (*CacheContextOptions) UseRedis

func (c *CacheContextOptions) UseRedis(instanceName string, fn func(cfg *cache.RedisConfigOptions)) *CacheContextOptions

type Claim

type Claim struct {
	Type  string
	Value any
}

Claim 表示一个 Claim

type ClaimsPrincipal

type ClaimsPrincipal struct {
	Subject              string    // 一般对应 nameidentifier 或 sub(JWT)
	Name                 string    // Display name
	Roles                []string  // 权限角色列表
	Claims               []Claim   // 所有的 Claim(通用扩展)
	IdentityProvider     string    // 身份提供者(如 AzureAD、Google、Internal 等)
	AuthenticationMethod string    // 认证方式(如 password、oauth、saml)
	AuthenticatedAt      time.Time // 认证时间
}

ClaimsPrincipal 表示用户身份和声明

func (*ClaimsPrincipal) AddClaim

func (cp *ClaimsPrincipal) AddClaim(key string, value interface{})

AddClaim 添加 Claim

func (*ClaimsPrincipal) AddRole

func (cp *ClaimsPrincipal) AddRole(role string)

AddRole 添加角色

func (*ClaimsPrincipal) Clone

func (cp *ClaimsPrincipal) Clone() *ClaimsPrincipal

Clone 克隆 ClaimsPrincipal 对象

func (*ClaimsPrincipal) FindFirst

func (cp *ClaimsPrincipal) FindFirst(key string) (interface{}, bool)

FindFirst 查找第一个 Claim, 返回 Claim 的值和是否存在

func (*ClaimsPrincipal) HasClaim

func (cp *ClaimsPrincipal) HasClaim(key string, value interface{}) bool

HasClaim 判断是否有指定 Claim, 返回 true 表示有指定 Claim

func (*ClaimsPrincipal) IsInRole

func (cp *ClaimsPrincipal) IsInRole(role string) bool

IsInRole 判断是否有指定角色, 返回 true 表示有指定角色

type ConcurrencyLimiter

type ConcurrencyLimiter struct {
	// contains filtered or unexported fields
}

ConcurrencyLimiter 并发限流器

func NewConcurrencyLimiter

func NewConcurrencyLimiter(options *ConcurrencyOptions) *ConcurrencyLimiter

func (*ConcurrencyLimiter) Release

func (l *ConcurrencyLimiter) Release(key string)

func (*ConcurrencyLimiter) TryAcquire

func (l *ConcurrencyLimiter) TryAcquire(key string) (bool, time.Duration)

type ConcurrencyOptions

type ConcurrencyOptions struct {
	PermitLimit          int
	QueueProcessingOrder QueueProcessingOrder
	QueueLimit           int
}

ConcurrencyOptions 并发限制选项

type CookieAuthenticationHandler

type CookieAuthenticationHandler struct {
	// contains filtered or unexported fields
}

CookieAuthenticationHandler Cookie 认证处理器

func (*CookieAuthenticationHandler) Authenticate

Authenticate 从请求中认证 Cookie

func (*CookieAuthenticationHandler) Scheme

func (h *CookieAuthenticationHandler) Scheme() string

Scheme 认证方案名称

type CookieOptions

type CookieOptions struct {
	Name              string
	Path              string
	Domain            string
	MaxAge            int
	Secure            bool
	HttpOnly          bool
	DataProtectionKey string // 数据保护密钥
}

CookieOptions 定义cookie的相关选项

type DataProtector

type DataProtector interface {
	Protect(data []byte) ([]byte, error)
	Unprotect(protectedData []byte) ([]byte, error)
}

DataProtector 数据保护接口,用于加密和解密认证票据

type DbContextOptions

type DbContextOptions struct {
	// contains filtered or unexported fields
}

DatabaseOptions 数据库选项

func (*DbContextOptions) UseMySQL

func (d *DbContextOptions) UseMySQL(instanceName string, fn func(cfg *database.MySQLConfigOptions)) *DbContextOptions

UseMySQL 注册 MySQL 数据库实例 若 instanceName 为空,则默认注册一个单库的实例,可通过实例直接注入 若 instanceName 非空,则注册一个显式命名的实例,使用 name 标签注入

func (*DbContextOptions) UsePostgresSQL

func (d *DbContextOptions) UsePostgresSQL(instanceName string, fn func(cfg *database.PostgresConfig)) *DbContextOptions

UsePostgresSQL 注册 Postgres 数据库实例 若 instanceName 为空,则默认注册一个单库的实例,可通过实例直接注入 若 instanceName 非空,则注册一个显式命名的实例,使用 name 标签注入

func (*DbContextOptions) UseSQLServer

func (d *DbContextOptions) UseSQLServer(instanceName string, fn func(cfg *database.DatabaseConfig)) *DbContextOptions

type EchoAuthenticationMiddleware

type EchoAuthenticationMiddleware struct {
	*AuthenticationOptions
	// contains filtered or unexported fields
}

EchoAuthenticationMiddleware echo 授权中间件

func (*EchoAuthenticationMiddleware) Handle

func (a *EchoAuthenticationMiddleware) Handle() echo.MiddlewareFunc

Handle 授权中间件处理逻辑

type EchoAuthorizationMiddleware

type EchoAuthorizationMiddleware struct {
	*AuthenticationOptions
	*AuthorizationOptions
	// contains filtered or unexported fields
}

EchoAuthorizationMiddleware echo 授权中间件

func (*EchoAuthorizationMiddleware) Handle

func (a *EchoAuthorizationMiddleware) Handle() echo.MiddlewareFunc

Handle 授权中间件处理函数

type EchoLocalizationMiddleware

type EchoLocalizationMiddleware struct {
	*LocalizationOptions
	// contains filtered or unexported fields
}

GinAuthorizationMiddleware 授权中间件

func (*EchoLocalizationMiddleware) Handle

func (l *EchoLocalizationMiddleware) Handle() echo.MiddlewareFunc

Handle 授权中间件处理函数

type EchoMiddleware

type EchoMiddleware interface {
	Handle() echo.MiddlewareFunc
}

EchoMiddleware echo中间件接口

type EchoRateLimitMiddleware

type EchoRateLimitMiddleware struct {
	// contains filtered or unexported fields
}

func (*EchoRateLimitMiddleware) Handle

func (m *EchoRateLimitMiddleware) Handle() echo.MiddlewareFunc

Handle 限流处理函数

type EchoWebApplication

type EchoWebApplication struct {
	*app.Application

	ServerOptions *ServerOptions
	// contains filtered or unexported fields
}

EchoWebApplication 实现 WebApplication 接口

func (*EchoWebApplication) Config

func (a *EchoWebApplication) Config() *viper.Viper

Config 获取配置对象

func (*EchoWebApplication) CreateRouteInitializer

func (a *EchoWebApplication) CreateRouteInitializer(handlerFunc any, group, path string, method RequestMethod) any

func (*EchoWebApplication) Env

func (a *EchoWebApplication) Env() *Environment

Environment 获取环境对象

func (*EchoWebApplication) Logger

func (a *EchoWebApplication) Logger() *zap.Logger

Logger 获取日志对象

func (*EchoWebApplication) MapGrpcServices

func (app *EchoWebApplication) MapGrpcServices(sevrs ...any) WebApplication

MapGrpcServices 注册 gRPC 服务

func (*EchoWebApplication) MapRouter

func (a *EchoWebApplication) MapRouter(routeFuncList ...any) WebApplication

MapRoutes 路由注册

func (*EchoWebApplication) Run

func (webapp *EchoWebApplication) Run()

func (*EchoWebApplication) Use

func (b *EchoWebApplication) Use(middleware ...any) WebApplication

UseMiddleware 注册中间件

func (*EchoWebApplication) UseAuthentication

func (a *EchoWebApplication) UseAuthentication() WebApplication

UseAuthentication 鉴权中间件

func (*EchoWebApplication) UseAuthorization

func (a *EchoWebApplication) UseAuthorization() WebApplication

UseAuthorization 授权中间件

func (*EchoWebApplication) UseCORS

func (a *EchoWebApplication) UseCORS(fn any) WebApplication

UseCORS CORS 支持

func (*EchoWebApplication) UseHealthCheck

func (a *EchoWebApplication) UseHealthCheck() WebApplication

UseHealthCheck 健康检查

func (*EchoWebApplication) UseLocalization

func (a *EchoWebApplication) UseLocalization() WebApplication

UseLocalization 配置国际化功能

func (*EchoWebApplication) UseLogger

func (a *EchoWebApplication) UseLogger() WebApplication

UseLogger 注册日志中间件, 用于记录请求日志

func (*EchoWebApplication) UseRateLimiter

func (a *EchoWebApplication) UseRateLimiter() WebApplication

UseRateLimit 配置限流功能

func (*EchoWebApplication) UseRecovery

func (a *EchoWebApplication) UseRecovery() WebApplication

UseRecovery 注册恢复中间件, 用于捕获 panic 并返回 500 错误

func (*EchoWebApplication) UseRouting

func (a *EchoWebApplication) UseRouting() WebApplication

UseRouting 配置路由

func (*EchoWebApplication) UseStaticFiles

func (a *EchoWebApplication) UseStaticFiles(urlPath, root string) WebApplication

UseStaticFiles 配置静态文件

func (*EchoWebApplication) UseSwagger

func (a *EchoWebApplication) UseSwagger() WebApplication

UseSwagger swagger支持

type Environment

type Environment struct {
	IsDevelopment bool
	Env           string
}

Environment is the struct for environment variables

type FixedWindowLimiter

type FixedWindowLimiter struct {
	// contains filtered or unexported fields
}

固定窗口限流器

func NewFixedWindowLimiter

func NewFixedWindowLimiter(options *FixedWindowOptions) *FixedWindowLimiter

func (*FixedWindowLimiter) Release

func (l *FixedWindowLimiter) Release(key string)

func (*FixedWindowLimiter) TryAcquire

func (l *FixedWindowLimiter) TryAcquire(key string) (bool, time.Duration)

type FixedWindowOptions

type FixedWindowOptions struct {
	PermitLimit          int
	Window               time.Duration
	QueueProcessingOrder QueueProcessingOrder
	QueueLimit           int
}

FixedWindowOptions 固定窗口选项

type GinAuthenticationMiddleware

type GinAuthenticationMiddleware struct {
	*AuthenticationOptions
	// contains filtered or unexported fields
}

GinAuthenticationMiddleware 授权中间件

func (*GinAuthenticationMiddleware) Handle

Handle 授权中间件处理逻辑

type GinAuthorizationMiddleware

type GinAuthorizationMiddleware struct {
	*AuthenticationOptions
	*AuthorizationOptions
	// contains filtered or unexported fields
}

GinAuthorizationMiddleware 授权中间件

func (*GinAuthorizationMiddleware) Handle

Handle 授权中间件处理函数

type GinLocalizationMiddleware

type GinLocalizationMiddleware struct {
	*LocalizationOptions
	// contains filtered or unexported fields
}

GinAuthorizationMiddleware 授权中间件

func (*GinLocalizationMiddleware) Handle

Handle 授权中间件处理函数

type GinMiddleware

type GinMiddleware interface {
	Handle() gin.HandlerFunc
}

GinMiddleware gin middleware interface

type GinRateLimitMiddleware

type GinRateLimitMiddleware struct {
	// contains filtered or unexported fields
}

func (*GinRateLimitMiddleware) Handle

Handle 限流处理函数

type GinWebApplication

type GinWebApplication struct {
	*app.Application

	ServerOptions *ServerOptions
	// contains filtered or unexported fields
}

GinWebApplication 实现 WebApplication 接口

func (*GinWebApplication) Config

func (a *GinWebApplication) Config() *viper.Viper

Config 获取配置实例

func (*GinWebApplication) CreateRouteInitializer

func (a *GinWebApplication) CreateRouteInitializer(handlerFunc any, group, path string, method RequestMethod) any

func (*GinWebApplication) Env

func (a *GinWebApplication) Env() *Environment

Environment 获取环境实例

func (*GinWebApplication) Logger

func (a *GinWebApplication) Logger() *zap.Logger

Logger 获取日志实例

func (*GinWebApplication) MapGrpcServices

func (webapp *GinWebApplication) MapGrpcServices(constructors ...any) WebApplication

MapGrpcServices 注册 gRPC 服务

func (*GinWebApplication) MapRouter

func (a *GinWebApplication) MapRouter(routeFuncList ...any) WebApplication

MapRoutes 注册路由

func (*GinWebApplication) Run

func (webapp *GinWebApplication) Run()

Run 启动 Web 应用程序

func (*GinWebApplication) Use

func (b *GinWebApplication) Use(middleware ...any) WebApplication

UseMiddleware 注册中间件

func (*GinWebApplication) UseAuthentication

func (a *GinWebApplication) UseAuthentication() WebApplication

UseAuthentication 鉴权中间件

func (*GinWebApplication) UseAuthorization

func (a *GinWebApplication) UseAuthorization() WebApplication

UseAuthorization 授权中间件

func (*GinWebApplication) UseCORS

func (a *GinWebApplication) UseCORS(fn any) WebApplication

UseCORS 配置跨域

func (*GinWebApplication) UseHealthCheck

func (a *GinWebApplication) UseHealthCheck() WebApplication

UseHealthCheck 配置健康检查

func (*GinWebApplication) UseLocalization

func (a *GinWebApplication) UseLocalization() WebApplication

UseLocalization 配置国际化功能

func (*GinWebApplication) UseLogger

func (a *GinWebApplication) UseLogger() WebApplication

UseLogger 注册日志中间件, 用于记录请求日志

func (*GinWebApplication) UseRateLimiter

func (a *GinWebApplication) UseRateLimiter() WebApplication

UseRateLimit 配置限流功能

func (*GinWebApplication) UseRecovery

func (a *GinWebApplication) UseRecovery() WebApplication

UseRecovery 注册恢复中间件, 用于捕获 panic 并返回 500 错误

func (*GinWebApplication) UseRouting

func (a *GinWebApplication) UseRouting() WebApplication

func (*GinWebApplication) UseStaticFiles

func (a *GinWebApplication) UseStaticFiles(urlPath, root string) WebApplication

UseStaticFiles 配置静态文件

func (*GinWebApplication) UseSwagger

func (a *GinWebApplication) UseSwagger() WebApplication

UseSwagger 配置Swagger

type GroupRouteConfig

type GroupRouteConfig struct {
	Prefix         string
	Schemes        []string
	Policies       []string
	RateLimiter    []string
	Routes         []*RouteConfig
	AllowAnonymous bool
}

GroupRouteConfig 分组路由配置

func (*GroupRouteConfig) MapDelete

func (group *GroupRouteConfig) MapDelete(path string, handler any) *RouteConfig

MapDelete 注册DELETE请求路由

func (*GroupRouteConfig) MapGet

func (group *GroupRouteConfig) MapGet(path string, handler any) *RouteConfig

MapGet 注册GET请求路由

func (*GroupRouteConfig) MapPatch

func (group *GroupRouteConfig) MapPatch(path string, handler any) *RouteConfig

MapPatch 注册PATCH请求路由

func (*GroupRouteConfig) MapPost

func (group *GroupRouteConfig) MapPost(path string, handler any) *RouteConfig

MapPost 注册POST请求路由

func (*GroupRouteConfig) MapPut

func (group *GroupRouteConfig) MapPut(path string, handler any) *RouteConfig

MapPut 注册PUT请求路由

func (*GroupRouteConfig) WithAllowAnonymous

func (group *GroupRouteConfig) WithAllowAnonymous() *GroupRouteConfig

WithAllowAnonymous 配置允许匿名访问

func (*GroupRouteConfig) WithAuthenticationScheme

func (group *GroupRouteConfig) WithAuthenticationScheme(schemes ...string) *GroupRouteConfig

registerPattern 注册路由模式到 httprouter

func (*GroupRouteConfig) WithAuthorizationPolicy

func (group *GroupRouteConfig) WithAuthorizationPolicy(policies ...string) *GroupRouteConfig

WithAuthorizationPolicy 配置授权策略

func (*GroupRouteConfig) WithRateLimiter

func (group *GroupRouteConfig) WithRateLimiter(limiters ...string) *GroupRouteConfig

WithRateLimiter 配置限流器

type GrpcService

type GrpcService interface {
	Register(server *grpc.Server)
}

GrpcService 定义 gRPC 服务接口

type JSONWebKey

type JSONWebKey struct {
	Kid string `json:"kid"`
	Kty string `json:"kty"`
	Use string `json:"use"`
	N   string `json:"n"`
	E   string `json:"e"`
	Alg string `json:"alg"`
}

JSONWebKey represents a JSON Web Key (JWK) as defined in RFC 7517.

type JSONWebKeySet

type JSONWebKeySet struct {
	Keys []JSONWebKey `json:"keys"`
}

JSONWebKeySet represents a JSON Web Key Set (JWKS) as defined in RFC 7517.

type JWTBearerAuthenticationHandler

type JWTBearerAuthenticationHandler struct {
	Options *JwtBearerOptions
}

JWTBearerAuthenticationHandler JWT Bearer 认证

func (*JWTBearerAuthenticationHandler) Authenticate

Authenticate 实现 AuthenticationHandler 接口

func (*JWTBearerAuthenticationHandler) Scheme

Scheme 实现 AuthenticationHandler 接口

type JwtBearerEvents

type JwtBearerEvents struct {
	OnMessageReceived      func(r *http.Request) (string, error)
	OnTokenValidated       func(principal *ClaimsPrincipal) error
	OnAuthenticationFailed func(err error) error
	OnChallenge            func(w http.ResponseWriter, r *http.Request, err error)
}

JwtBearerEvents defines the events that can be subscribed to JwtBearerOptions.

type JwtBearerOptions

type JwtBearerOptions struct {
	RequireHttpsMetadata       bool
	MetadataAddress            string
	Authority                  string
	Audience                   string
	Challenge                  string
	Events                     *JwtBearerEvents
	BackchannelHttpClient      *http.Client
	BackchannelTimeout         time.Duration
	RefreshOnIssuerKeyNotFound bool
	TokenValidationParameters  TokenValidationParameters
	SaveToken                  bool
	IncludeErrorDetails        bool
	MapInboundClaims           bool
	AutomaticRefreshInterval   time.Duration
	RefreshInterval            time.Duration
	// contains filtered or unexported fields
}

JwtBearerOptions defines the options for JwtBearer authentication.

func (*JwtBearerOptions) FetchJWKS

func (j *JwtBearerOptions) FetchJWKS() error

FeatchJWKS fetches the JSON Web Key Set (JWKS) for an issuer.

func (*JwtBearerOptions) FetchOpenIDConfig

func (j *JwtBearerOptions) FetchOpenIDConfig() error

FetchOpenIDConfig fetches the OpenID Connect configuration for an issuer.

type LocalizationFileType

type LocalizationFileType string
const (
	LocalizationFileTypeJSON LocalizationFileType = ".json"
	LocalizationFileTypeToml LocalizationFileType = ".toml"
)

type LocalizationOptions

type LocalizationOptions struct {
	// 默认语言
	DefaultLanguage string
	// 支持的语言列表
	SupportedLanguages []string
	// 翻译文件目录
	TranslationsDir string
	// Bundle 实例
	Bundle *i18n.Bundle
	// 文件类型,支持 "json" 和 "toml"
	FileType LocalizationFileType
}

type LocalizerBuilder

type LocalizerBuilder struct {
	// contains filtered or unexported fields
}

I18nBuilder 国际化构建器

func (*LocalizerBuilder) Build

func (b *LocalizerBuilder) Build() (*i18n.Bundle, error)

Build 构建国际化服务

type OpenIDConfig

type OpenIDConfig struct {
	Issuer  string `json:"issuer"`
	JwksURI string `json:"jwks_uri"`
	Expires time.Time
}

OpenIDConfig represents the OpenID Connect configuration for an issuer.

type QueueProcessingOrder

type QueueProcessingOrder int

QueueProcessingOrder 队列处理顺序

const (
	// OldestFirst 先进先出
	OldestFirst QueueProcessingOrder = iota
	// NewestFirst 后进先出
	NewestFirst
)

type RateLimitOptions

type RateLimitOptions struct {
	DefaultPolicy string // 默认限流策略名称
	// contains filtered or unexported fields
}

RateLimitOptions 限流配置选项

func (*RateLimitOptions) AddConcurrencyLimiter

func (opt *RateLimitOptions) AddConcurrencyLimiter(name string, configure func(*ConcurrencyOptions))

AddConcurrencyLimiter 添加并发限流器

func (*RateLimitOptions) AddFixedWindowLimiter

func (opt *RateLimitOptions) AddFixedWindowLimiter(name string, configure func(*FixedWindowOptions))

AddFixedWindowLimiter 添加固定窗口限流器

func (*RateLimitOptions) AddSlidingWindowLimiter

func (opt *RateLimitOptions) AddSlidingWindowLimiter(name string, configure func(*SlidingWindowOptions))

AddSlidingWindowLimiter 添加滑动窗口限流器

func (*RateLimitOptions) AddTokenBucketLimiter

func (opt *RateLimitOptions) AddTokenBucketLimiter(name string, configure func(*TokenBucketOptions))

AddTokenBucketLimiter 添加令牌桶限流器

type RateLimitPolicy

type RateLimitPolicy string

RateLimitPolicy 限流策略类型

const (
	// FixedWindow 固定窗口
	FixedWindow RateLimitPolicy = "fixed"
	// SlidingWindow 滑动窗口
	SlidingWindow RateLimitPolicy = "sliding"
	// TokenBucket 令牌桶
	TokenBucket RateLimitPolicy = "token"
	// Concurrency 并发数
	Concurrency RateLimitPolicy = "concurrent"
)

type RateLimiter

type RateLimiter interface {
	// TryAcquire 尝试获取访问权限
	TryAcquire(key string) (bool, time.Duration)
	// Release 释放资源(用于并发限流)
	Release(key string)
}

RateLimiter 限流器接口

type RequestMethod

type RequestMethod string

RequestMethod is a type for HTTP request method

const (
	GET     RequestMethod = "GET"
	POST    RequestMethod = "POST"
	PUT     RequestMethod = "PUT"
	DELETE  RequestMethod = "DELETE"
	PATCH   RequestMethod = "PATCH"
	HEAD    RequestMethod = "HEAD"
	OPTIONS RequestMethod = "OPTIONS"
)

type Route

type Route struct {
	Path    string
	Methods []RequestMethod
}

Route is a struct for a route definition

type RouteAuthenticationSchemes

type RouteAuthenticationSchemes struct {
	Routes  []Route  // 鉴权路由
	Schemes []string // 鉴权方案列表
}

RouteAuthenticationSchemes 表示路由和认证方案的关联

type RouteAuthorizePolicies

type RouteAuthorizePolicies struct {
	Routes   []Route  // 路由列表
	Policies []string // 授权策略列表
}

RouteAuthorizePolicies 表示路由和授权策略的关联

type RouteConfig

type RouteConfig struct {
	Path           string
	Method         RequestMethod
	Handler        any
	Schemes        []string
	Policies       []string
	RateLimiter    []string
	AllowAnonymous bool
}

路由配置

func (*RouteConfig) WithAllowAnonymous

func (config *RouteConfig) WithAllowAnonymous() *RouteConfig

WithAllowAnonymous 配置允许匿名访问

func (*RouteConfig) WithAuthenticationScheme

func (config *RouteConfig) WithAuthenticationScheme(schemes ...string) *RouteConfig

WithAuthenticationScheme 配置认证方案

func (*RouteConfig) WithAuthorizationPolicy

func (config *RouteConfig) WithAuthorizationPolicy(policies ...string) *RouteConfig

WithAuthorizationPolicy 配置授权策略

func (*RouteConfig) WithRateLimiter

func (config *RouteConfig) WithRateLimiter(limiters ...string) *RouteConfig

WithRateLimiter 配置限流器

type RouteKey

type RouteKey struct {
	Path   string
	Method string
	Glob   glob.Glob // 预编译
}

RouteKey is a struct for a route key definition

type RouteRateLimitPolicies

type RouteRateLimitPolicies struct {
	Routes          []Route  // 路由列表
	RateLimitPolicy []string // 授权策略列表
}

RouteAuthorizePolicies 表示路由和授权策略的关联

type RouterOptions

type RouterOptions struct {
	// contains filtered or unexported fields
}

func (*RouterOptions) MapDelete

func (opts *RouterOptions) MapDelete(path string, handler any) *RouteConfig

MapDelete 注册DELETE请求路由

func (*RouterOptions) MapGet

func (opts *RouterOptions) MapGet(path string, handler any) *RouteConfig

MapGet 注册GET请求路由

func (*RouterOptions) MapGroup

func (opts *RouterOptions) MapGroup(prefix string) *GroupRouteConfig

MapGroup 注册分组路由

func (*RouterOptions) MapPatch

func (opts *RouterOptions) MapPatch(path string, handler any) *RouteConfig

MapPatch 注册PATCH请求路由

func (*RouterOptions) MapPost

func (opts *RouterOptions) MapPost(path string, handler any) *RouteConfig

MapPost 注册POST请求路由

func (*RouterOptions) MapPut

func (opts *RouterOptions) MapPut(path string, handler any) *RouteConfig

MapPut 注册PUT请求路由

type ServerOptions

type ServerOptions struct {
	HttpPort          string
	GrpcPort          string
	Environment       string
	UseDefaultRecover bool
	UseDefaultLogger  bool
}

ServerOptions is the struct for server options

type SlidingWindowLimiter

type SlidingWindowLimiter struct {
	// contains filtered or unexported fields
}

SlidingWindowLimiter 滑动窗口限流器

func NewSlidingWindowLimiter

func NewSlidingWindowLimiter(options *SlidingWindowOptions) *SlidingWindowLimiter

func (*SlidingWindowLimiter) Release

func (l *SlidingWindowLimiter) Release(key string)

func (*SlidingWindowLimiter) TryAcquire

func (l *SlidingWindowLimiter) TryAcquire(key string) (bool, time.Duration)

type SlidingWindowOptions

type SlidingWindowOptions struct {
	PermitLimit          int
	Window               time.Duration
	SegmentsPerWindow    int
	QueueProcessingOrder QueueProcessingOrder
	QueueLimit           int
}

SlidingWindowOptions 滑动窗口选项

type TokenBucketLimiter

type TokenBucketLimiter struct {
	// contains filtered or unexported fields
}

TokenBucketLimiter 令牌桶限流器

func NewTokenBucketLimiter

func NewTokenBucketLimiter(options *TokenBucketOptions) *TokenBucketLimiter

func (*TokenBucketLimiter) Release

func (l *TokenBucketLimiter) Release(key string)

func (*TokenBucketLimiter) TryAcquire

func (l *TokenBucketLimiter) TryAcquire(key string) (bool, time.Duration)

type TokenBucketOptions

type TokenBucketOptions struct {
	TokenLimit           int
	QueueProcessingOrder QueueProcessingOrder
	QueueLimit           int
	ReplenishmentPeriod  time.Duration
	TokensPerPeriod      int
	AutoReplenishment    bool
}

TokenBucketOptions 令牌桶选项

type TokenValidationParameters

type TokenValidationParameters struct {
	ValidAudience     string
	ValidIssuer       string
	RequireExpiration bool
	ClockSkew         time.Duration
	SigningKey        []byte // 单个签名密钥(对称或非对称)

	ValidateIssuer           bool
	ValidateAudience         bool
	ValidateLifetime         bool
	ValidateIssuerSigningKey bool
	RequireExpirationTime    bool
	// contains filtered or unexported fields
}

TokenValidationParameters defines the options for validating a JWT token.

type WebApplication

type WebApplication interface {
	Logger() *zap.Logger
	Config() *viper.Viper
	Env() *Environment
	Run()
	Use(...any) WebApplication
	UseSwagger() WebApplication
	UseCORS(any) WebApplication
	UseStaticFiles(urlPath, root string) WebApplication
	UseHealthCheck() WebApplication
	UseAuthentication() WebApplication
	UseAuthorization() WebApplication
	UseRecovery() WebApplication
	UseLogger() WebApplication
	UseLocalization() WebApplication
	UseRateLimiter() WebApplication
	UseRouting() WebApplication
	MapRouter(...any) WebApplication
	MapGrpcServices(...any) WebApplication
}

WebApplication is the interface that defines the behavior of a web application.

func NewEchoWebApplication

func NewEchoWebApplication(options WebApplicationOptions) WebApplication

NewEchoWebApplication 创建一个新的 EchoWebApplication

type WebApplicationBuilder

type WebApplicationBuilder struct {
	*app.ApplicationBuilder
	*app.Application
	*RouterOptions

	Config    *viper.Viper
	Logger    *zap.Logger
	Container []fx.Option
	// contains filtered or unexported fields
}

WebApplicationBuilder 构建web应用

func NewBuilder

func NewBuilder() *WebApplicationBuilder

NewWebAppBuilder 创建WebApplicationBuilder

func (*WebApplicationBuilder) AddAuthentication

func (b *WebApplicationBuilder) AddAuthentication(options func(*AuthenticationOptions)) *WebApplicationBuilder

AddAuthentication 添加鉴权方案

func (*WebApplicationBuilder) AddAuthorization

func (b *WebApplicationBuilder) AddAuthorization(fn func(*AuthorizationOptions)) *WebApplicationBuilder

AddAuthorization 添加授权策略

func (*WebApplicationBuilder) AddCacheContext

func (b *WebApplicationBuilder) AddCacheContext(fn func(*CacheContextOptions)) *WebApplicationBuilder

AddCacheContext 添加缓存配置

func (*WebApplicationBuilder) AddDbContext

func (b *WebApplicationBuilder) AddDbContext(fn func(*DbContextOptions)) *WebApplicationBuilder

AddDbContext 添加数据库配置

func (*WebApplicationBuilder) AddLocalization

func (b *WebApplicationBuilder) AddLocalization(fn func(*LocalizationOptions)) *WebApplicationBuilder

func (*WebApplicationBuilder) AddRateLimiter

func (b *WebApplicationBuilder) AddRateLimiter(configure func(*RateLimitOptions)) *WebApplicationBuilder

AddRateLimiter 添加限流配置

func (*WebApplicationBuilder) AddRouter

AddRouter 添加路由配置

func (*WebApplicationBuilder) Build

Build 构建应用

type WebApplicationOptions

type WebApplicationOptions struct {
	Config        *viper.Viper
	Logger        *zap.Logger
	Container     []fx.Option
	App           *app.Application
	RouterOptions *RouterOptions
}

WebApplicationOptions is the struct for web application options

Jump to

Keyboard shortcuts

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