Documentation
¶
Index ¶
- func BadRequest(message string) error
- func Forbidden(message string) error
- func InternalError(message string) error
- func NewHttpException(code int, message string) error
- func NotFound(message string) error
- func Unauthorized(message string) error
- type Application
- type ApplicationBuilder
- type Binder
- type BodyReader
- type CORSConfig
- type ChainableMiddleware
- type Config
- type ConfigLoader
- type ConfigProvider
- type ConfigWatcher
- type Configurable
- type ConfigurableMiddleware
- type Context
- type ContextRunner
- type Controller
- type CronScheduler
- type DataWriter
- type Disposable
- type EndpointRouteBuilder
- type Env
- type ExceptionFilter
- type Field
- type FieldImpl
- type FullRequestReader
- type FullResponseWriter
- type GRPCContext
- type GRPCServer
- type GlobalLogger
- type GroupCreator
- type Guard
- type GuardFunc
- type HTTPServer
- type HeaderWrittenChecker
- type Host
- type HostApplication
- type HostApplicationBuilder
- type HostBuilder
- type HttpError
- type HttpErrorFactory
- type HttpException
- type Interceptor
- type InterceptorFunc
- type JSONWriter
- type JobHandler
- type JobInfo
- type Logger
- type LoggerConfig
- type LoggerMiddlewareConfig
- type LoggerWriter
- type MapRoute
- type MessageType
- type Middleware
- type MiddlewareApp
- type MiddlewareFunc
- type MiddlewareRegistrar
- type MiddlewareUser
- type PathParamsReader
- type Pipe
- type PipeFunc
- type ProtocolAdapter
- type QueryReader
- type QueueConfig
- type QueueFactory
- type QueueStats
- type QueueTask
- type RawRequest
- type RawResponseWriter
- type ReadOnlyContext
- type RequestReader
- type RequestSetter
- type ResultStore
- type Route
- type RouteAdder
- type RouteBuilder
- type RouteGetter
- type RouteGroup
- type RouteHandler
- type RouteMatcher
- type Router
- type SSEContext
- type SSEHandler
- type SSEServer
- type SchedulerConfig
- type Scope
- type SecurityConfig
- type ServiceCollection
- type ServiceDescriptor
- type ServiceLifetime
- type ServiceRegistrar
- type ServiceResolver
- type StatusWriter
- type StringWriter
- type TaskHandler
- type TaskOption
- type TaskOptions
- type TaskQueue
- type TaskResult
- type TypedConfig
- type ValueStore
- type WSContext
- type WSHandler
- type WSServer
- type WebApplication
- type WebApplicationBuilder
- type WebHost
- type WebHostBuilder
- type WriteOnlyContext
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewHttpException ¶
NewHttpException 创建自定义HTTP异常
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 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 ¶
ConfigLoader 配置加载接口
type ConfigProvider ¶
ConfigProvider 配置提供者接口
type ConfigWatcher ¶
ConfigWatcher 配置监听接口
type ConfigurableMiddleware ¶
type ConfigurableMiddleware[T any] interface { Configure(config T) Middleware }
ConfigurableMiddleware 可配置的中间件接口
type Context ¶
type Context interface {
ContextRunner
FullRequestReader
FullResponseWriter
RawResponseWriter
RequestSetter
ValueStore
}
Context 完整上下文接口(Handler使用)
type ContextRunner ¶
ContextRunner 上下文运行器接口
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 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 ¶
ExceptionFilter 异常过滤器接口
type FieldImpl ¶
type FieldImpl struct {
// contains filtered or unexported fields
}
FieldImpl 日志字段实现
type FullRequestReader ¶
type FullRequestReader interface {
RequestReader
RawRequest
PathParamsReader
QueryReader
BodyReader
Binder
}
FullRequestReader 完整请求读取接口(组合)
type FullResponseWriter ¶
type FullResponseWriter interface {
StatusWriter
JSONWriter
StringWriter
DataWriter
HeaderWrittenChecker
}
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 ¶
GlobalLogger 全局日志接口
type GroupCreator ¶
type GroupCreator interface {
Group(prefix string) RouteGroup
}
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 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 HttpErrorFactory ¶
type HttpErrorFactory interface {
BadRequest(message string) error
Forbidden(message string) error
NotFound(message string) error
InternalError(message string) error
}
HttpErrorFactory HTTP错误工厂接口
type HttpException ¶
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 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 ¶
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 ¶
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 ¶
MiddlewareFunc 中间件函数类型
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 ¶
PathParamsReader 路径参数读取接口
type ProtocolAdapter ¶
type ProtocolAdapter interface {
Name() string
Scheme() string
Start(addr string) error
Stop(ctx context.Context) error
Running() bool
}
ProtocolAdapter 协议适配器接口
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 RawResponseWriter ¶
type RawResponseWriter interface {
ResponseWriter() http.ResponseWriter
}
type ReadOnlyContext ¶
type ReadOnlyContext interface {
ContextRunner
RawRequest
RequestReader
PathParamsReader
QueryReader
ValueStore
}
ReadOnlyContext 只读上下文接口(中间件前置处理)
type RequestReader ¶
RequestReader 请求基本信息读取接口
type RequestSetter ¶
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 RouteMatcher ¶
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 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 ¶
SchedulerConfig 调度器配置
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 TaskHandler ¶
TaskHandler 后台任务处理函数类型
type TaskOptions ¶
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 ¶
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 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 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 只写上下文接口(错误处理)