abstract

package
v0.0.0-...-e13c845 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BadRequest

func BadRequest(message string) error

BadRequest 创建400错误

func Forbidden

func Forbidden(message string) error

Forbidden 创建403错误

func InternalError

func InternalError(message string) error

InternalError 创建500错误

func NewHttpException

func NewHttpException(code int, message string) error

NewHttpException 创建自定义HTTP异常

func NotFound

func NotFound(message string) error

NotFound 创建404错误

func Unauthorized

func Unauthorized(message string) error

Unauthorized 创建401错误

Types

type Application

type Application interface {
	Services() ServiceCollection
	Configuration() Config
	Environment() Env
	Logging() Logger
	Run() error
	RunAsync() <-chan error
	Start() error
	StartAsync() <-chan error
	Stop() error
	Shutdown(ctx context.Context) error
	WaitForShutdown() error
}

Application 通用应用接口

type ApplicationBuilder

type ApplicationBuilder interface {
	Services() ServiceCollection
	Configuration() Config
	Environment() Env
	Logging() Logger
	Build() Application
}

ApplicationBuilder 通用应用构建器接口(ASP.NET Core风格)

type Binder

type Binder interface {
	Bind(v any) error
}

Binder 请求体绑定接口

type BodyReader

type BodyReader interface {
	Body() []byte
}

BodyReader 请求体读取接口

type CORSConfig

type CORSConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig CORS配置

type ChainableMiddleware

type ChainableMiddleware interface {
	Middleware
	Next(ctx Context) error
}

ChainableMiddleware 可链式组合的中间件接口

type Config

type Config interface {
	GetString(key string) string
	GetInt(key string) int
	GetBool(key string) bool
	Get(key string) any
	GetDefault(key string, defaultValue any) any
	Unmarshal(key string, v any) error
}

Config 配置接口

type ConfigLoader

type ConfigLoader interface {
	Load() error
	LoadFile(path string) error
}

ConfigLoader 配置加载接口

type ConfigProvider

type ConfigProvider interface {
	Name() string
	Provide() (map[string]any, error)
}

ConfigProvider 配置提供者接口

type ConfigWatcher

type ConfigWatcher interface {
	Watch(callback func(key string, value any))
	StopWatch()
}

ConfigWatcher 配置监听接口

type Configurable

type Configurable interface {
	Configure(cfg Config) error
}

Configurable 可配置接口

type ConfigurableMiddleware

type ConfigurableMiddleware[T any] interface {
	Configure(config T) Middleware
}

ConfigurableMiddleware 可配置的中间件接口

type Context

Context 完整上下文接口(Handler使用)

type ContextRunner

type ContextRunner interface {
	Context() context.Context
}

ContextRunner 上下文运行器接口

type Controller

type Controller interface {
	Routes(r Router)
}

Controller 控制器接口

type CronScheduler

type CronScheduler interface {
	AddJob(cronExpr string, name string, handler JobHandler) error
	AddIntervalJob(interval time.Duration, name string, handler JobHandler) error
	RemoveJob(name string) error
	RunJob(name string) error
	Start() error
	Stop(ctx context.Context) error
	Jobs() []JobInfo
}

CronScheduler 定时任务调度器接口

type DataWriter

type DataWriter interface {
	Data(code int, contentType string, data []byte) error
}

type Disposable

type Disposable interface {
	Dispose() error
}

Disposable 可释放接口

type EndpointRouteBuilder

type EndpointRouteBuilder interface {
	MapGet(path string, handler any) RouteBuilder
	MapPost(path string, handler any) RouteBuilder
	MapPut(path string, handler any) RouteBuilder
	MapDelete(path string, handler any) RouteBuilder
	MapPatch(path string, handler any) RouteBuilder
	MapControllers() EndpointRouteBuilder
	MapControllerRoute(name string, pattern string, defaults map[string]string) EndpointRouteBuilder
	MapAreaControllerRoute(name string, areaName string, pattern string, defaults map[string]string) EndpointRouteBuilder
	MapDefaultControllerRoute() EndpointRouteBuilder
}

EndpointRouteBuilder 端点路由构建器接口

type Env

type Env interface {
	// Get 获取环境变量,不存在返回空字符串
	Get(key string) string

	// GetOrDefault 获取环境变量,不存在返回默认值
	GetOrDefault(key, defaultValue string) string

	// Has 检查环境变量是否存在
	Has(key string) bool

	// All 返回所有环境变量
	All() map[string]string

	// Set 设置环境变量(主要用于测试场景)
	Set(key, value string)

	// Unset 删除环境变量(主要用于测试场景)
	Unset(key string)
}

Env 环境变量接口 用于读取和管理系统环境变量,支持依赖注入和测试替换

type ExceptionFilter

type ExceptionFilter interface {
	Catch(ctx Context, err error) error
}

ExceptionFilter 异常过滤器接口

type Field

type Field interface {
	Key() string
	Value() any
}

Field 日志字段接口

func Any

func Any(key string, value any) Field

func Err

func Err(err error) Field

常用字段工厂函数

func Int

func Int(key string, value int) Field

func NewField

func NewField(key string, value any) Field

func String

func String(key, value string) Field

type FieldImpl

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

FieldImpl 日志字段实现

func (*FieldImpl) Key

func (f *FieldImpl) Key() string

func (*FieldImpl) Value

func (f *FieldImpl) Value() any

type FullRequestReader

type FullRequestReader interface {
	RequestReader
	RawRequest
	PathParamsReader
	QueryReader
	BodyReader
	Binder
}

FullRequestReader 完整请求读取接口(组合)

type GRPCContext

type GRPCContext interface {
	ContextRunner
	// 请求信息
	Method() string
	Service() string
	// 消息
	RequestMessage() any
	ResponseMessage() any
	// 元数据
	Metadata(key string) string
	SetHeader(key, value string)
	SetTrailer(key, value string)
	// 错误
	SetError(err error)
}

GRPCContext gRPC上下文接口

type GRPCServer

type GRPCServer interface {
	ProtocolAdapter
	RegisterService(desc any, impl any)
	Use(interceptor any)
}

GRPCServer gRPC服务器接口

type GlobalLogger

type GlobalLogger interface {
	SetGlobalLogger(log Logger)
	GetGlobalLogger() Logger
}

GlobalLogger 全局日志接口

type GroupCreator

type GroupCreator interface {
	Group(prefix string) RouteGroup
}

type Guard

type Guard interface {
	CanActivate(ctx Context) bool
}

Guard 守卫接口

type GuardFunc

type GuardFunc func(ctx Context) bool

GuardFunc 守卫函数类型

func (GuardFunc) CanActivate

func (f GuardFunc) CanActivate(ctx Context) bool

CanActivate 实现 Guard 接口

type HTTPServer

type HTTPServer interface {
	ProtocolAdapter
	RouteGetter
	GroupCreator
	Static(prefix string, root string)
	StaticFile(path string, file string)
}

HTTPServer HTTP服务器接口

type HeaderWrittenChecker

type HeaderWrittenChecker interface {
	HeaderWritten() bool
}

type Host

type Host interface {
	CreateBuilder(args ...string) WebApplicationBuilder
}

Host 主机接口

type HostApplication

type HostApplication interface {
	Application
}

HostApplication 主机应用接口

type HostApplicationBuilder

type HostApplicationBuilder interface {
	ConfigureServices(configure func(ServiceCollection)) HostApplicationBuilder
	Configure(configure func(WebApplicationBuilder)) HostApplicationBuilder
	Build() WebApplication
}

HostApplicationBuilder 主机应用构建器接口

type HostBuilder

type HostBuilder interface {
	UseContentRoot(path string) HostBuilder
	UseEnvironment(env string) HostBuilder
	ContentRoot() string
	Environment() string
	Args() []string
	SetArgs(args []string)
}

HostBuilder 主机构建器接口

type HttpError

type HttpError struct {
	Code int
	Msg  string
}

HttpError HTTP异常结构体(同时满足接口)

func (*HttpError) Error

func (e *HttpError) Error() string

func (*HttpError) Message

func (e *HttpError) Message() string

func (*HttpError) Status

func (e *HttpError) Status() int

type HttpErrorFactory

type HttpErrorFactory interface {
	BadRequest(message string) error
	Unauthorized(message string) error
	Forbidden(message string) error
	NotFound(message string) error
	InternalError(message string) error
}

HttpErrorFactory HTTP错误工厂接口

type HttpException

type HttpException interface {
	Error() string
	Status() int
	Message() string
}

HttpException HTTP异常接口

type Interceptor

type Interceptor interface {
	Intercept(ctx Context, next RouteHandler) (any, error)
}

Interceptor 拦截器接口

type InterceptorFunc

type InterceptorFunc func(ctx Context, next RouteHandler) (any, error)

InterceptorFunc 拦截器函数类型

func (InterceptorFunc) Intercept

func (f InterceptorFunc) Intercept(ctx Context, next RouteHandler) (any, error)

Intercept 实现 Interceptor 接口

type JSONWriter

type JSONWriter interface {
	JSON(code int, v any) error
}

type JobHandler

type JobHandler func(ctx context.Context) error

JobHandler 任务处理函数类型

type JobInfo

type JobInfo interface {
	Name() string
	Schedule() string
	NextRun() time.Time
	LastRun() time.Time
	Running() bool
	RunCount() int64
	ErrorCount() int64
}

JobInfo 任务信息接口

type Logger

type Logger interface {
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)
}

Logger 日志接口

type LoggerConfig

type LoggerConfig struct {
	Level      string
	Output     io.Writer
	TimeFormat string
	MaxSize    int
	MaxBackups int
	MaxAge     int
	Compress   bool
	FileName   string
}

LoggerConfig 日志配置

type LoggerMiddlewareConfig

type LoggerMiddlewareConfig struct {
	SkipPaths []string
	Formatter func(ctx Context, latency time.Duration) string
}

LoggerMiddlewareConfig 日志中间件配置

type LoggerWriter

type LoggerWriter interface {
	Write(p []byte) (n int, err error)
}

LoggerWriter 日志写入接口

type MapRoute

type MapRoute interface {
	MapGet(path string, handler any) RouteBuilder
	MapPost(path string, handler any) RouteBuilder
	MapPut(path string, handler any) RouteBuilder
	MapDelete(path string, handler any) RouteBuilder
	MapPatch(path string, handler any) RouteBuilder
}

MapRoute 路由映射接口

type MessageType

type MessageType int

MessageType WebSocket消息类型

const (
	TextMessage   MessageType = 1
	BinaryMessage MessageType = 2
	CloseMessage  MessageType = 8
	PingMessage   MessageType = 9
	PongMessage   MessageType = 10
)

type Middleware

type Middleware interface {
	Handle(ctx Context, next func() error) error
}

Middleware 中间件接口

type MiddlewareApp

type MiddlewareApp interface {
	UseCORS(cfg *CORSConfig) Application
	UseRecovery() Application
	UseRequestID(headerName string) Application
	UseRateLimit(limit int, window time.Duration) Application
	UseGzip(level int) Application
	UseSecurity(cfg *SecurityConfig) Application
	UseTimeout(timeout time.Duration) Application
	UseScope() Application
}

MiddlewareApp 中间件应用接口

type MiddlewareFunc

type MiddlewareFunc func(ctx Context, next func() error) error

MiddlewareFunc 中间件函数类型

func (MiddlewareFunc) Handle

func (f MiddlewareFunc) Handle(ctx Context, next func() error) error

Handle 实现 Middleware 接口

type MiddlewareRegistrar

type MiddlewareRegistrar interface {
	AddCORS(config any) MiddlewareRegistrar
	AddRecovery(config any) MiddlewareRegistrar
	AddLogging(config any) MiddlewareRegistrar
	AddRateLimit(config any) MiddlewareRegistrar
	AddGzip(config any) MiddlewareRegistrar
	AddSecurity(config any) MiddlewareRegistrar
	AddRequestID(config any) MiddlewareRegistrar
	AddTimeout(config any) MiddlewareRegistrar
}

MiddlewareRegistrar 中间件注册接口

type MiddlewareUser

type MiddlewareUser interface {
	UseCORS() MiddlewareUser
	UseRecovery() MiddlewareUser
	UseLogging() MiddlewareUser
	UseRateLimit() MiddlewareUser
	UseGzip() MiddlewareUser
	UseSecurity() MiddlewareUser
	UseRequestID() MiddlewareUser
	UseTimeout() MiddlewareUser
	Application() WebApplication
}

MiddlewareUser 中间件使用接口(Mixin)

type PathParamsReader

type PathParamsReader interface {
	Param(name string) string
}

PathParamsReader 路径参数读取接口

type Pipe

type Pipe interface {
	Transform(value any, ctx Context) (any, error)
}

Pipe 管道接口

type PipeFunc

type PipeFunc func(value any, ctx Context) (any, error)

PipeFunc 管道函数类型

func (PipeFunc) Transform

func (f PipeFunc) Transform(value any, ctx Context) (any, error)

Transform 实现 Pipe 接口

type ProtocolAdapter

type ProtocolAdapter interface {
	Name() string
	Scheme() string
	Start(addr string) error
	Stop(ctx context.Context) error
	Running() bool
}

ProtocolAdapter 协议适配器接口

type QueryReader

type QueryReader interface {
	Query(name string) string
}

QueryReader Query参数读取接口

type QueueConfig

type QueueConfig struct {
	Workers     int
	MaxRetry    int
	Concurrency int
	Timeout     time.Duration
	Queues      map[string]int
}

QueueConfig 队列配置

type QueueFactory

type QueueFactory interface {
	CreateQueue(name string, opts QueueConfig) (TaskQueue, error)
	CreateScheduler(opts SchedulerConfig) (CronScheduler, error)
}

QueueFactory 队列工厂接口

type QueueStats

type QueueStats interface {
	Name() string
	Pending() int64
	Active() int64
	Scheduled() int64
	Retry() int64
	Processed() int64
	Failed() int64
	ProcessedAt() time.Time
}

QueueStats 队列统计接口

type QueueTask

type QueueTask interface {
	ID() string
	Type() string
	Payload() []byte
	Priority() int
	Queue() string
	Metadata() map[string]string
	CreatedAt() time.Time
}

QueueTask 队列任务接口

type RawRequest

type RawRequest interface {
	Request() *http.Request
}

RawRequest 原生请求对象访问接口

type RawResponseWriter

type RawResponseWriter interface {
	ResponseWriter() http.ResponseWriter
}

type ReadOnlyContext

ReadOnlyContext 只读上下文接口(中间件前置处理)

type RequestReader

type RequestReader interface {
	Method() string
	Path() string
	Header(name string) string
}

RequestReader 请求基本信息读取接口

type RequestSetter

type RequestSetter interface {
	SetRequest(r *http.Request)
}

RequestSetter 原生请求对象设置接口

type ResultStore

type ResultStore interface {
	Set(ctx context.Context, taskID string, result TaskResult, ttl time.Duration) error
	Get(ctx context.Context, taskID string) (TaskResult, error)
	Delete(ctx context.Context, taskID string) error
}

ResultStore 结果存储接口

type Route

type Route interface {
	Method() string
	Path() string
	Handler() RouteHandler
}

type RouteAdder

type RouteAdder interface {
	AddRoute(method, path string, handler RouteHandler) RouteBuilder
}

type RouteBuilder

type RouteBuilder interface {
	Guard(guard Guard) RouteBuilder
	Interceptor(interceptor Interceptor) RouteBuilder
	Pipe(pipe Pipe) RouteBuilder
}

type RouteGetter

type RouteGetter interface {
	GET(path string, handler RouteHandler) RouteBuilder
	POST(path string, handler RouteHandler) RouteBuilder
	PUT(path string, handler RouteHandler) RouteBuilder
	DELETE(path string, handler RouteHandler) RouteBuilder
	PATCH(path string, handler RouteHandler) RouteBuilder
	OPTIONS(path string, handler RouteHandler) RouteBuilder
}

type RouteGroup

type RouteGroup interface {
	RouteGetter
}

type RouteHandler

type RouteHandler func(ctx Context) error

type RouteMatcher

type RouteMatcher interface {
	Match(req *http.Request) (Route, map[string]string)
}

type Router

type Router interface {
	RouteGetter
	GroupCreator
	RouteMatcher
}

type SSEContext

type SSEContext interface {
	ContextRunner
	// 客户端信息
	ClientID() string
	// 发送事件
	Event(event string, data string) error
	EventWithID(event string, id string, data string) error
	// 注释(用于心跳)
	Comment(comment string) error
	// 状态
	IsConnected() bool
	// 房间
	Room() string
	JoinRoom(room string)
	LeaveRoom(room string)
}

SSEContext SSE上下文接口

type SSEHandler

type SSEHandler func(ctx SSEContext) error

SSEHandler SSE处理函数类型

type SSEServer

type SSEServer interface {
	ProtocolAdapter
	SSE(path string, handler SSEHandler)
	Broadcast(event string, data string) error
	BroadcastTo(room string, event string, data string) error
	SendTo(clientID string, event string, data string) error
	GetClient(clientID string) SSEContext
}

SSEServer SSE服务器接口

type SchedulerConfig

type SchedulerConfig struct {
	Timezone    string
	Concurrency int
	Timeout     time.Duration
}

SchedulerConfig 调度器配置

type Scope

type Scope interface {
	Dispose()
	IsDisposed() bool
}

Scope 作用域接口

type SecurityConfig

type SecurityConfig struct {
	XSSProtection         bool
	ContentTypeNosniff    bool
	XFrameOptions         string
	HSTSMaxAge            int
	HSTSIncludeSubdomains bool
	ContentSecurityPolicy string
	ReferrerPolicy        string
	PermissionsPolicy     string
}

SecurityConfig 安全配置

type ServiceCollection

type ServiceCollection interface {
	ServiceResolver
	ServiceRegistrar
	MiddlewareRegistrar
}

ServiceCollection 服务集合接口(组合)

type ServiceDescriptor

type ServiceDescriptor interface {
	ServiceType() reflect.Type
	Instance() any
	Factory() any
	Lifetime() ServiceLifetime
}

ServiceDescriptor 服务描述符接口

type ServiceLifetime

type ServiceLifetime int

ServiceLifetime 服务生命周期类型

const (
	Singleton ServiceLifetime = iota
	Scoped
	Transient
)

type ServiceRegistrar

type ServiceRegistrar interface {
	AddSingleton(instance any) ServiceRegistrar
	AddSingletonFactory(serviceType reflect.Type, factory any) ServiceRegistrar
	AddScoped(serviceType reflect.Type, factory any) ServiceRegistrar
	AddTransient(serviceType reflect.Type, factory any) ServiceRegistrar
}

ServiceRegistrar 服务注册接口

type ServiceResolver

type ServiceResolver interface {
	GetService(serviceType reflect.Type) any
	GetRequiredService(serviceType reflect.Type) any
}

ServiceResolver 服务解析接口

type StatusWriter

type StatusWriter interface {
	Status(code int)
}

type StringWriter

type StringWriter interface {
	String(code int, s string) error
}

type TaskHandler

type TaskHandler func(ctx context.Context, task *QueueTask) error

TaskHandler 后台任务处理函数类型

type TaskOption

type TaskOption func(*TaskOptions)

TaskOption 任务选项函数类型

func WithMaxRetry

func WithMaxRetry(n int) TaskOption

WithMaxRetry 设置最大重试次数

func WithTimeout

func WithTimeout(d time.Duration) TaskOption

WithTimeout 设置超时时间

func WithUnique

func WithUnique() TaskOption

WithUnique 设置唯一任务

type TaskOptions

type TaskOptions struct {
	MaxRetry  int
	Timeout   time.Duration
	Unique    bool
	Retention time.Duration
}

TaskOptions 任务选项

type TaskQueue

type TaskQueue interface {
	Enqueue(task QueueTask, opts ...TaskOption) error
	EnqueueDelayed(task QueueTask, delay time.Duration, opts ...TaskOption) error
	EnqueueAt(task QueueTask, at time.Time, opts ...TaskOption) error
	RegisterHandler(taskType string, handler TaskHandler) error
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	Stats() QueueStats
	Name() string
}

TaskQueue 后台任务队列接口

type TaskResult

type TaskResult interface {
	TaskID() string
	Status() string
	Result() []byte
	Error() string
	At() time.Time
}

TaskResult 任务结果接口

type TypedConfig

type TypedConfig interface {
	GetString(key string) string
	GetInt(key string) int
	GetBool(key string) bool
}

TypedConfig 泛型配置接口

type ValueStore

type ValueStore interface {
	Set(key string, value any)
	Get(key string) any
}

ValueStore 值存储接口

type WSContext

type WSContext interface {
	ContextRunner
	// 连接信息
	ClientID() string
	RemoteAddr() string
	// 发送消息
	SendText(msg string) error
	SendBinary(data []byte) error
	SendJSON(v any) error
	// 接收消息
	Receive() (MessageType, []byte, error)
	ReceiveJSON(v any) error
	// 连接管理
	Close() error
	CloseWithStatus(code int, reason string) error
	IsClosed() bool
	// 房间
	Room() string
	JoinRoom(room string)
	LeaveRoom(room string)
}

WSContext WebSocket上下文接口

type WSHandler

type WSHandler func(ctx WSContext) error

WSHandler WebSocket处理函数类型

type WSServer

type WSServer interface {
	ProtocolAdapter
	WS(path string, handler WSHandler)
	Broadcast(msg []byte) error
	BroadcastText(msg string) error
	BroadcastTo(room string, msg []byte) error
	SendTo(clientID string, msg []byte) error
	GetRoom(room string) []WSContext
	GetClient(clientID string) WSContext
}

WSServer WebSocket服务器接口

type WebApplication

type WebApplication interface {
	Application
	Router
	Use(middleware Middleware) WebApplication
	UseGlobalGuards(guards ...Guard) WebApplication
	UseGlobalInterceptors(interceptors ...Interceptor) WebApplication
	UseGlobalPipes(pipes ...Pipe) WebApplication
	UseGlobalFilters(filters ...ExceptionFilter) WebApplication
	MapGet(path string, handler any) RouteBuilder
	MapPost(path string, handler any) RouteBuilder
	MapPut(path string, handler any) RouteBuilder
	MapDelete(path string, handler any) RouteBuilder
	MapPatch(path string, handler any) RouteBuilder
	Map(method string, path string, handler any) RouteBuilder
	MapGroup(prefix string) RouteGroup
	UseRouting() WebApplication
	UseEndpoints(configure func(EndpointRouteBuilder)) WebApplication
	UseAuthentication() WebApplication
	UseAuthorization() WebApplication
	Urls() []string
	Addresses() []string
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Listen(addr string) error
}

WebApplication Web应用接口

type WebApplicationBuilder

type WebApplicationBuilder interface {
	Services() ServiceCollection
	Configuration() Config
	Environment() Env
	Logging() Logger
	WebHost() WebHostBuilder
	Build() WebApplication
}

WebApplicationBuilder Web应用构建器接口

type WebHost

type WebHost interface {
	Start() error
	Stop(ctx context.Context) error
	Addresses() []string
}

WebHost Web主机接口

type WebHostBuilder

type WebHostBuilder interface {
	UseUrls(urls ...string) WebHostBuilder
	ConfigureKestrel(configure func(interface{})) WebHostBuilder
	Build() WebHost
}

WebHostBuilder Web主机构建器接口

type WriteOnlyContext

type WriteOnlyContext interface {
	ContextRunner
	FullResponseWriter
	RawResponseWriter
	ValueStore
}

WriteOnlyContext 只写上下文接口(错误处理)

Jump to

Keyboard shortcuts

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