lrpc

package module
v0.0.0-...-1788606 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: AGPL-3.0 Imports: 24 Imported by: 4

README

LRPC - Lightweight RPC Framework

Go Version License

一个基于 fasthttp 的轻量级、高性能 RPC 框架

✨ 特性

  • 🚀 高性能: 基于 fasthttp 构建,性能优于标准库 net/http
  • 🎯 灵活路由: 支持静态路由、参数路由和通配符路由
  • 🔌 中间件生态: 内置丰富的中间件支持(认证、缓存、压缩、限流等)
  • 🛡️ 类型安全: 使用 Go 泛型提供类型安全的路由和中间件
  • 🎨 反射处理: 自动处理请求解析和响应序列化
  • 🔄 连接池: 内置连接池和对象池优化
  • 📊 可观测性: 内置指标收集和健康检查
  • 🔧 可扩展: 插件系统支持自定义功能扩展

📦 安装

go get github.com/lazygophers/lrpc

🚀 快速开始

基础示例
package main

import (
    "github.com/lazygophers/lrpc"
    "github.com/lazygophers/log"
)

type HelloRequest struct {
    Name string `json:"name"`
}

type HelloResponse struct {
    Message string `json:"message"`
}

func main() {
    app := lrpc.New(lrpc.Config{
        Name: "hello-service",
        Port: 8080,
    })

    // 简单处理器
    app.Get("/hello", func(ctx *lrpc.Ctx) error {
        return ctx.SendString("Hello, World!")
    })

    // 带请求/响应类型的处理器
    app.Post("/hello", func(ctx *lrpc.Ctx, req *HelloRequest) (*HelloResponse, error) {
        return &HelloResponse{
            Message: "Hello, " + req.Name,
        }, nil
    })

    log.Fatal(app.Listen())
}

📚 路由系统

支持的路由类型
// 静态路由
app.Get("/api/users", handler)

// 参数路由
app.Get("/api/users/:id", handler)

// 通配符路由
app.Get("/static/*", handler)
路由分组
api := app.Group("/api")
{
    // GET /api/users
    api.Get("/users", listUsers)

    // POST /api/users
    api.Post("/users", createUser)

    v1 := api.Group("/v1")
    {
        // GET /api/v1/info
        v1.Get("/info", getInfo)
    }
}
HTTP 方法
app.Get("/path", handler)      // GET
app.Post("/path", handler)     // POST
app.Put("/path", handler)      // PUT
app.Delete("/path", handler)   // DELETE
app.Patch("/path", handler)    // PATCH
app.Head("/path", handler)     // HEAD
app.Options("/path", handler)  // OPTIONS
app.Any("/path", handler)      // All methods

🔧 中间件

内置中间件
认证
import "github.com/lazygophers/lrpc/middleware/auth"

// JWT 认证
app.Use(auth.JWT(auth.JWTConfig{
    SigningKey:    "your-secret-key",
    SigningMethod: "HS256",
}))

// Basic 认证
app.Use(auth.BasicAuth(auth.BasicAuthConfig{
    Users: map[string]string{
        "admin": "password",
    },
}))
安全
import "github.com/lazygophers/lrpc/middleware/security"

// CORS
app.Use(security.CORS(security.CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
}))

// 安全头
app.Use(security.SecurityHeaders(security.DefaultSecurityHeadersConfig))

// 限流
app.Use(security.RateLimit(security.RateLimitMiddlewareConfig{
    Rate:   100,
    Window: time.Minute,
}))
压缩
import "github.com/lazygophers/lrpc/middleware/compress"

app.Use(compress.Compress(compress.Config{
    Level:     compress.LevelDefault,
    MinLength: 1024,
}))
缓存
import "github.com/lazygophers/lrpc/middleware/cache"

app.Use(cache.Cache(cache.CacheConfig{
    MaxAge: 3600,
    Public: true,
}))
指标收集
import "github.com/lazygophers/lrpc/middleware/metrics"

collector := metrics.NewCollector()
app.Use(metrics.Metrics(metrics.Config{
    Collector: collector,
    SlowRequestConfig: metrics.SlowRequestConfig{
        Threshold: time.Second,
    },
}))

// 获取指标
stats := collector.GetMetrics()
健康检查
import "github.com/lazygophers/lrpc/middleware/health"

checker := health.NewChecker()
checker.AddCheck("database", health.DatabaseCheck(db.Ping))
checker.AddCheck("cache", health.CacheCheck(cache.Ping))

app.Get("/health", func(ctx *lrpc.Ctx) error {
    return ctx.SendJson(checker.RunChecks())
})
自定义中间件
func Logger() lrpc.HandlerFunc {
    return func(ctx *lrpc.Ctx) error {
        start := time.Now()

        // 处理请求
        err := ctx.Next()

        // 记录日志
        log.Infof("method=%s path=%s duration=%v",
            ctx.Method(), ctx.Path(), time.Since(start))

        return err
    }
}

app.Use(Logger())

🗃️ 数据存储

数据库 (GORM)
import "github.com/lazygophers/lrpc/middleware/storage/db"

// 初始化数据库
dbClient, err := db.NewClient(&db.Config{
    Driver: "mysql",
    DSN:    "user:pass@tcp(localhost:3306)/dbname",
})

// 注入到 context
app.Use(db.Middleware(dbClient))

// 在处理器中使用
func handler(ctx *lrpc.Ctx) error {
    db := db.GetDB(ctx)

    var users []User
    db.Find(&users)

    return ctx.SendJson(users)
}
缓存 (Redis/Memory)
import "github.com/lazygophers/lrpc/middleware/storage/cache/redis"

// Redis 缓存
cache, err := redis.NewClient(&redis.Config{
    Addr:     "localhost:6379",
    Password: "",
    DB:       0,
})

// 使用
err = cache.Set("key", value, time.Hour)
val, err := cache.Get("key")
etcd
import "github.com/lazygophers/lrpc/middleware/storage/etcd"

client, err := etcd.NewClient(etcd.Config{
    Endpoints: []string{"localhost:2379"},
})

// 服务发现
discovery := etcd.NewServiceDiscovery(client)

🔌 gRPC 集成

HTTP 到 gRPC 桥接
import "github.com/lazygophers/lrpc/middleware/grpc"

bridge := grpc.DefaultHTTPtoGRPCBridge
adapter := grpc.NewGRPCServiceAdapter(bridge)

// 将 gRPC handler 适配为 HTTP handler
app.Post("/api/grpc", adapter.UnaryHandler(grpcHandler, reqType))
gRPC 客户端
import "github.com/lazygophers/lrpc/middleware/grpc"

config := grpc.DefaultClientConfig
config.Address = "localhost:9090"

conn, err := grpc.NewClient(config)

🔄 连接池

自定义连接池
import "github.com/lazygophers/lrpc/middleware/pool"

pool, err := pool.NewPool(
    pool.PoolConfig{
        MaxConns:    100,
        MinConns:    10,
        MaxIdleTime: 5 * time.Minute,
        MaxLifetime: 1 * time.Hour,
    },
    func() (interface{}, error) {
        // 创建连接
        return createConnection()
    },
    func(conn interface{}) error {
        // 关闭连接
        return conn.Close()
    },
)

// 使用连接
conn, err := pool.Acquire()
defer pool.Release(conn)
服务器连接池配置
import "github.com/lazygophers/lrpc/middleware/pool"

// 高性能配置
config := pool.HighPerformanceConfig()

// 低内存配置
config := pool.LowMemoryConfig()

// 应用到服务器
pool.ApplyServerPoolConfig(server, config)

🔧 插件系统

创建插件
import "github.com/lazygophers/lrpc/middleware/plugin"

type MyPlugin struct {
    *plugin.BasePlugin
}

func NewMyPlugin() *MyPlugin {
    return &MyPlugin{
        BasePlugin: plugin.NewBasePlugin("my-plugin", "1.0.0"),
    }
}

func (p *MyPlugin) Init(config interface{}) error {
    // 初始化逻辑
    return p.BasePlugin.Init(config)
}

func (p *MyPlugin) Start() error {
    // 启动逻辑
    return p.BasePlugin.Start()
}
使用插件管理器
manager := plugin.NewManager()

// 注册插件
myPlugin := NewMyPlugin()
manager.Register(myPlugin)

// 初始化所有插件
manager.InitAll(configs)

// 启动所有插件
manager.StartAll()

// 停止所有插件
defer manager.StopAll()

📊 性能优化

对象池

框架内部使用 sync.Pool 优化内存分配:

  • Context 对象池
  • Buffer 池
  • 连接池
性能建议
  1. 使用连接池: 重用数据库和 gRPC 连接
  2. 启用压缩: 对大响应启用 gzip 压缩
  3. 配置限流: 防止服务过载
  4. 监控指标: 使用 metrics 中间件监控性能
  5. 调整 fasthttp 配置: 根据负载调整并发和缓冲区大小

🧪 测试

框架包含完整的测试套件:

# 运行所有测试(单元测试)
go test ./...

# 运行特定包的测试
go test ./middleware/auth/...

# 查看覆盖率
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.out

# 运行集成测试(需要启动 Docker 服务)
make test-setup
make test-integration
make test-teardown

# 运行基准测试
go test ./... -bench=. -benchmem

测试说明

  • 单元测试使用 mock 模式,不需要外部依赖
  • 集成测试需要 Docker 服务(Redis, MySQL, ClickHouse),通过 make test 自动管理
  • db 包当前使用 mock 测试,覆盖率约 74%

📖 示例

查看 examples/ 目录获取更多示例:

🛠️ 配置选项

应用配置
app := lrpc.New(lrpc.Config{
    Name:              "my-service",
    Port:              8080,
    ReadTimeout:       30 * time.Second,
    WriteTimeout:      30 * time.Second,
    MaxRequestBodySize: 4 * 1024 * 1024, // 4MB
    EnableMetrics:     true,
    EnableHealth:      true,
})
中间件配置

每个中间件都有可配置的选项,参见各个中间件包的文档。

🤝 贡献

欢迎贡献!请遵循以下步骤:

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启 Pull Request
开发指南
  • 遵循 Go 代码规范
  • 添加单元测试
  • 更新文档
  • 运行 golangci-lint run 检查代码质量

📝 License

本项目采用 MIT 许可证 - 详见 LICENSE 文件

🙏 致谢

📧 联系方式


⭐ 如果这个项目对你有帮助,请给个 Star!

Documentation

Index

Constants

View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"

	HeaderFeaturePolicy           = "Feature-Policy"
	HeaderPermissionsPolicy       = "Permissions-Policy"
	HeaderPublicKeyPins           = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXDownloadOptions        = "X-Download-Options"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderXPoweredBy              = "X-Powered-By"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderLastEventID             = "Last-Event-ID"
	HeaderNEL                     = "NEL"
	HeaderPingFrom                = "Ping-From"
	HeaderPingTo                  = "Ping-To"
	HeaderReportTo                = "Report-To"
	HeaderTE                      = "TE"
	HeaderTrailer                 = "Trailer"
	HeaderTransferEncoding        = "Transfer-Encoding"
	HeaderSecWebSocketAccept      = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions  = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey         = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol    = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion     = "Sec-WebSocket-Version"
	HeaderAcceptPatch             = "Accept-Patch"
	HeaderAcceptPushPolicy        = "Accept-Push-Policy"
	HeaderAcceptSignature         = "Accept-Signature"
	HeaderAltSvc                  = "Alt-Svc"
	HeaderDate                    = "Date"
	HeaderIndex                   = "Index"
	HeaderLargeAllocation         = "Large-Allocation"
	HeaderLink                    = "Link"
	HeaderPushPolicy              = "Push-Policy"
	HeaderRetryAfter              = "Retry-After"
	HeaderServerTiming            = "Server-Timing"
	HeaderSignature               = "Signature"
	HeaderSignedHeaders           = "Signed-Headers"
	HeaderSourceMap               = "SourceMap"
	HeaderUpgrade                 = "Upgrade"
	HeaderXDNSPrefetchControl     = "X-DNS-Prefetch-Control"
	HeaderXPingback               = "X-Pingback"
	HeaderXRequestID              = "X-Request-ID"
	HeaderXRequestedWith          = "X-Requested-With"
	HeaderXRobotsTag              = "X-Robots-Tag"
	HeaderXUACompatible           = "X-UA-Compatible"

	HeaderTrace = "X-Trace"
	HeaderToken = "X-Token"
	HeaderTime  = "X-Time"
)
View Source
const (
	MIMETextXML             = "text/xml"
	MIMETextHTML            = "text/html"
	MIMETextPlain           = "text/plain"
	MIMETextJavaScript      = "text/javascript"
	MIMEApplicationXML      = "application/xml"
	MIMEApplicationJSON     = "application/json"
	MIMEApplicationProtobuf = "application/protobuf"

	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"

	MIMETextXMLCharsetUTF8               = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8              = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8             = "text/plain; charset=utf-8"
	MIMETextJavaScriptCharsetUTF8        = "text/javascript; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationProtobufCharsetUTF8   = "application/protobuf; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

Variables

View Source
var DefaultRecoverConfig = RecoverConfig{
	EnableStackTrace: true,
	StackTraceHandler: func(ctx *Ctx, err interface{}, stack []byte) {
		log.Errorf("[Panic Recovered] %v\nStack Trace:\n%s", err, string(stack))
	},
	ErrorHandler: nil,
}

DefaultRecoverConfig is the default Recover middleware config

View Source
var DiscoveryClient = func(c *core.ServiceDiscoveryClient) (Client, *fasthttp.Request) {
	panic("you should registe with discovery github.com/lazygophers/lrpc/middleware/service_discovery")
}
View Source
var EmptyListenHandler = func(a *App, c *listenConfig) {}
View Source
var ErrRouteNotFound = fmt.Errorf("route not found")

ErrRouteNotFound indicates that no route was found for the given path

Functions

func Call

func Call(ctx *Ctx, c *core.ServiceDiscoveryClient, req proto.Message, rsp proto.Message) error

Types

type App

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

func NewApp

func NewApp(c ...*Config) *App

func (*App) AcquireCtx

func (p *App) AcquireCtx(ctx *fasthttp.RequestCtx) *Ctx

func (*App) AddRoute

func (p *App) AddRoute(r *Route, opts ...RouteOption)

func (*App) AddRoutes

func (p *App) AddRoutes(rs []*Route, opts ...RouteOption)

func (*App) Connect

func (p *App) Connect(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) DELETE

func (app *App) DELETE(path string, handlers ...HandlerFunc) error

DELETE registers a DELETE route

func (*App) Delete

func (p *App) Delete(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) ErrorHandler

func (p *App) ErrorHandler(c *fasthttp.RequestCtx, err error)

func (*App) GET

func (app *App) GET(path string, handlers ...HandlerFunc) error

GET registers a GET route

func (*App) Get

func (p *App) Get(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Group

func (app *App) Group(prefix string, handlers ...HandlerFunc) *Group

Group creates a route group with prefix

func (*App) HEAD

func (app *App) HEAD(path string, handlers ...HandlerFunc) error

HEAD registers a HEAD route

func (*App) Handle

func (p *App) Handle(method, path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Handler

func (p *App) Handler(c *fasthttp.RequestCtx)

Handler is the main request handler that sets up tracing and calls ServeHTTP

func (*App) Head

func (p *App) Head(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Hooks

func (p *App) Hooks() *Hooks

func (*App) ListenAndServe

func (p *App) ListenAndServe(port int, handlers ...ListenHandler) (err error)

func (*App) OPTIONS

func (app *App) OPTIONS(path string, handlers ...HandlerFunc) error

OPTIONS registers an OPTIONS route

func (*App) OnListen

func (p *App) OnListen(logic func(ListenData) error)

func (*App) OnRoute

func (p *App) OnRoute(route func(*Route) error)

func (*App) OnShutdown

func (p *App) OnShutdown(logic func(ListenData))

func (*App) Options

func (p *App) Options(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) PATCH

func (app *App) PATCH(path string, handlers ...HandlerFunc) error

PATCH registers a PATCH route

func (*App) POST

func (app *App) POST(path string, handlers ...HandlerFunc) error

POST registers a POST route

func (*App) PUT

func (app *App) PUT(path string, handlers ...HandlerFunc) error

PUT registers a PUT route

func (*App) Patch

func (p *App) Patch(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Post

func (p *App) Post(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Put

func (p *App) Put(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) ReleaseCtx

func (p *App) ReleaseCtx(ctx *Ctx)

func (*App) ServeHTTP

func (app *App) ServeHTTP(ctx *fasthttp.RequestCtx)

ServeHTTP handles HTTP requests using the routing system

func (*App) ToHandlerFunc

func (p *App) ToHandlerFunc(logic any) HandlerFunc

func (*App) Trace

func (p *App) Trace(path string, handler HandlerFunc, opts ...RouteOption)

func (*App) Use

func (app *App) Use(handlers ...HandlerFunc)

Use adds global middleware to all routers

type BaseResponse

type BaseResponse struct {
	Code    int32  `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
	Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
	Data    any    `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
	Hint    string `protobuf:"bytes,4,opt,name=hint,proto3" json:"hint,omitempty"`
}

type Client

type Client interface {
	Do(req *fasthttp.Request, resp *fasthttp.Response) error
}

type Config

type Config struct {
	Name string

	OnError func(ctx *Ctx, err error)

	// 用于统一的封包、权限等处理
	AfterHandlerFuncWithRef func(ctx *Ctx, data reflect.Value, err error)
	AfterHandlerFunc        func(ctx *Ctx, err error)

	// MaxRequestBodySize sets the maximum request body size (0 = unlimited)
	MaxRequestBodySize int

	// EnableCompression enables automatic response compression
	EnableCompression bool

	// CompressionLevel sets the compression level
	CompressionLevel int

	// CompressionMinLength sets minimum response size to compress
	CompressionMinLength int

	// ServerPoolConfig configures the server connection pool
	ServerPoolConfig *pool.ServerPoolConfig
}

type Ctx

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

func NewCtxTools

func NewCtxTools() *Ctx

func (*Ctx) AllParams

func (p *Ctx) AllParams() map[string]string

AllParams returns all route parameters

func (*Ctx) AllQueries

func (p *Ctx) AllQueries() map[string]string

AllQueries returns all query parameters

func (*Ctx) Body

func (p *Ctx) Body() []byte

func (*Ctx) BodyEmpty

func (p *Ctx) BodyEmpty() bool

func (*Ctx) BodyParser

func (p *Ctx) BodyParser(o any) (err error)

func (*Ctx) ClearCookie

func (p *Ctx) ClearCookie(name string, path string)

ClearCookie clears a cookie

func (*Ctx) Context

func (p *Ctx) Context() *fasthttp.RequestCtx

func (*Ctx) Cookie

func (p *Ctx) Cookie(name string) string

Cookie gets a cookie value by name

func (*Ctx) FormFile

func (p *Ctx) FormFile(key string) (*multipart.FileHeader, error)

FormFile gets a file from multipart form

func (*Ctx) GetLocal

func (p *Ctx) GetLocal(key string) any

func (*Ctx) Header

func (p *Ctx) Header(key string) string

func (*Ctx) IsBodyStream

func (p *Ctx) IsBodyStream() bool

func (*Ctx) Method

func (p *Ctx) Method() string

func (*Ctx) MultipartForm

func (p *Ctx) MultipartForm() (*multipart.Form, error)

MultipartForm gets the multipart form

func (*Ctx) Next

func (p *Ctx) Next() error

Next executes the next handler in the middleware chain

func (*Ctx) Param

func (p *Ctx) Param(key string) string

func (*Ctx) Path

func (p *Ctx) Path() string

func (*Ctx) Query

func (p *Ctx) Query(key string) string

func (*Ctx) QueryBool

func (p *Ctx) QueryBool(key string, defaultValue ...bool) bool

QueryBool gets a query parameter as bool

func (*Ctx) QueryInt

func (p *Ctx) QueryInt(key string, defaultValue ...int) int

QueryInt gets a query parameter as int

func (*Ctx) Reset

func (p *Ctx) Reset()

func (*Ctx) SaveFile

func (p *Ctx) SaveFile(fileHeader *multipart.FileHeader, path string) error

SaveFile saves an uploaded file to a path

func (*Ctx) Send

func (p *Ctx) Send(body []byte)

func (*Ctx) SendJson

func (p *Ctx) SendJson(o any) error

func (*Ctx) SendStatus

func (p *Ctx) SendStatus(status int)

func (*Ctx) SendString

func (p *Ctx) SendString(s string)

func (*Ctx) SetCookie

func (p *Ctx) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie sets a cookie

func (*Ctx) SetHeader

func (p *Ctx) SetHeader(key string, value string)

func (*Ctx) SetLocal

func (p *Ctx) SetLocal(key string, value any)

func (*Ctx) SetParam

func (p *Ctx) SetParam(key, value string)

SetParam sets a route parameter (for compatibility with new routing)

func (*Ctx) SetTraceID

func (p *Ctx) SetTraceID(traceID ...string)

func (*Ctx) TraceID

func (p *Ctx) TraceID() string

type Group

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

Group represents a route group

func (*Group) DELETE

func (g *Group) DELETE(path string, handlers ...HandlerFunc) error

DELETE registers a DELETE route in the group

func (*Group) GET

func (g *Group) GET(path string, handlers ...HandlerFunc) error

GET registers a GET route in the group

func (*Group) Group

func (g *Group) Group(prefix string, handlers ...HandlerFunc) *Group

Group creates a sub-group

func (*Group) HEAD

func (g *Group) HEAD(path string, handlers ...HandlerFunc) error

HEAD registers a HEAD route in the group

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handlers ...HandlerFunc) error

OPTIONS registers an OPTIONS route in the group

func (*Group) PATCH

func (g *Group) PATCH(path string, handlers ...HandlerFunc) error

PATCH registers a PATCH route in the group

func (*Group) POST

func (g *Group) POST(path string, handlers ...HandlerFunc) error

POST registers a POST route in the group

func (*Group) PUT

func (g *Group) PUT(path string, handlers ...HandlerFunc) error

PUT registers a PUT route in the group

func (*Group) Use

func (g *Group) Use(handlers ...HandlerFunc) *Group

Use adds middleware to the group

type HandlerFunc

type HandlerFunc func(ctx *Ctx) error

func BodyLimit

func BodyLimit(maxSize int) HandlerFunc

BodyLimit returns a middleware that limits request body size

func MergeHandler

func MergeHandler(handlers ...HandlerFunc) HandlerFunc

func Recover

func Recover(config ...RecoverConfig) HandlerFunc

Recover returns a middleware that recovers from panics

type Hooks

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

func (*Hooks) OnListen

func (p *Hooks) OnListen(logic func(ListenData) error)

func (*Hooks) OnRoute

func (p *Hooks) OnRoute(route func(*Route) error)

func (*Hooks) OnShutdown

func (p *Hooks) OnShutdown(logic func(ListenData))

type ListenData

type ListenData struct {
	Host string
	Port string
	TLS  bool
}

type ListenHandler

type ListenHandler func(a *App, c *listenConfig)

func ListenWithIp

func ListenWithIp(ip string) ListenHandler

func ListenWithLan

func ListenWithLan(prev6 ...bool) ListenHandler

func ListenWithLocal

func ListenWithLocal(usev6 ...bool) ListenHandler

type MatchResult

type MatchResult struct {
	Node   *RouteNode
	Params map[string]string
}

MatchResult contains the result of a route match

type ParamConstraint

type ParamConstraint struct {
	Type  string         // int, string, uuid, regex, digit, etc.
	Min   *int           // min value for int, min length for string
	Max   *int           // max value for int, max length for string
	Len   *int           // fixed length for string
	Regex *regexp.Regexp // regex pattern
	Enum  []string       // enum values
}

ParamConstraint defines parameter validation rules

type RecoverConfig

type RecoverConfig struct {
	// EnableStackTrace enables printing stack trace
	EnableStackTrace bool

	// StackTraceHandler allows custom stack trace handling
	StackTraceHandler func(ctx *Ctx, err interface{}, stack []byte)

	// ErrorHandler allows custom error response
	ErrorHandler func(ctx *Ctx, err interface{})
}

RecoverConfig defines the config for Recover middleware

type Route

type Route struct {
	Method string
	Path   string

	Handler HandlerFunc

	Before, After []HandlerFunc

	// 可以存储一些类似于权限等信息,会在调用前写入到 local 中
	Extra map[string]any
}

type RouteNode

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

RouteNode represents a node in the route tree

type RouteOption

type RouteOption func(r *Route)

func RouteWithAfter

func RouteWithAfter(after HandlerFunc) RouteOption

func RouteWithBefore

func RouteWithBefore(before HandlerFunc) RouteOption

func RouteWithExtra

func RouteWithExtra(extra map[string]any) RouteOption

func RouteWithMergeExtra

func RouteWithMergeExtra(merge map[string]any) RouteOption

func RouteWithPrefix

func RouteWithPrefix(prefix string) RouteOption

type RouteParam

type RouteParam struct {
	Name       string
	Constraint *ParamConstraint
}

RouteParam defines a route parameter

type RouteType

type RouteType int

RouteType defines the type of route segment

const (
	RouteTypeStatic   RouteType = iota // /users/list
	RouteTypeTyped                     // /users/{id:int}
	RouteTypeParam                     // /users/{id}
	RouteTypeWildcard                  // /users/*
	RouteTypeCatchAll                  // /users/**
)

type Router

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

Router manages routes and middleware

func NewRouter

func NewRouter() *Router

NewRouter creates a new router

type SearchResult

type SearchResult[M any] struct {
	Item M

	Params map[string]string
}

type SearchTree

type SearchTree[M any] struct {
	// contains filtered or unexported fields
}

func NewSearchTree

func NewSearchTree[M any]() *SearchTree[M]

func (*SearchTree[M]) Add

func (p *SearchTree[M]) Add(route string, item M)

func (*SearchTree[M]) Search

func (p *SearchTree[M]) Search(route string) (*SearchResult[M], bool)

Directories

Path Synopsis
middleware
core
Package core 提供列表查询选项的处理框架
Package core 提供列表查询选项的处理框架
xerror
Package xerror 提供了结构化的错误处理机制,支持: - 错误码管理和注册 - 国际化错误消息 - HTTP 错误码集成 - 错误链支持(Go 1.13+)
Package xerror 提供了结构化的错误处理机制,支持: - 错误码管理和注册 - 国际化错误消息 - HTTP 错误码集成 - 错误链支持(Go 1.13+)

Jump to

Keyboard shortcuts

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