一个基于 fasthttp 的轻量级、高性能 RPC 框架
- 🚀 高性能: 基于 fasthttp 构建,性能优于标准库 net/http
- 🎯 灵活路由: 支持静态路由、参数路由和通配符路由
- 🔌 中间件生态: 内置丰富的中间件支持(认证、缓存、压缩、限流等)
- 🛡️ 类型安全: 使用 Go 泛型提供类型安全的路由和中间件
- 🎨 反射处理: 自动处理请求解析和响应序列化
- 🔄 连接池: 内置连接池和对象池优化
- 📊 可观测性: 内置指标收集和健康检查
- 🔧 可扩展: 插件系统支持自定义功能扩展
go get github.com/lazygophers/lrpcpackage 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)
}
}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 methodsimport "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())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)
}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")import "github.com/lazygophers/lrpc/middleware/storage/etcd"
client, err := etcd.NewClient(etcd.Config{
Endpoints: []string{"localhost:2379"},
})
// 服务发现
discovery := etcd.NewServiceDiscovery(client)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))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 池
- 连接池
- 使用连接池: 重用数据库和 gRPC 连接
- 启用压缩: 对大响应启用 gzip 压缩
- 配置限流: 防止服务过载
- 监控指标: 使用 metrics 中间件监控性能
- 调整 fasthttp 配置: 根据负载调整并发和缓冲区大小
框架包含完整的测试套件:
# 运行所有测试
go test ./...
# 运行特定包的测试
go test ./middleware/auth/...
# 查看覆盖率
go test ./... -cover
# 运行基准测试
go test ./... -bench=. -benchmem测试覆盖率统计:
- 总体代码: 21,206 行
- 测试代码: 16,123 行
- 测试文件: 36 个
- 平均覆盖率: ~68.8%
查看 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,
})每个中间件都有可配置的选项,参见各个中间件包的文档。
欢迎贡献!请遵循以下步骤:
- Fork 项目
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启 Pull Request
- 遵循 Go 代码规范
- 添加单元测试
- 更新文档
- 运行
golangci-lint run检查代码质量
本项目采用 MIT 许可证 - 详见 LICENSE 文件
- Issues: GitHub Issues
- Discussions: GitHub Discussions
⭐ 如果这个项目对你有帮助,请给个 Star!