servora

module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT

README

Servora

Go Reference GitHub release Go Report Card License Ask DeepWiki

简体中文

servora 是一个基于 Go Kratos 的微服务快速开发框架,采用 Proto First 开发方式,提供按域划分的框架能力(core/transport/security/obs/infra/)、自定义 protoc 插件与 CLI 工具(cmd/),以及框架级公共 Proto 定义(api/protos/)。

本仓库是 Servora-Kit 组织的核心框架库,不包含具体业务微服务。业务微服务请参考:

核心能力

  • 共享基础库:认证、授权、审计、配置引导、消息代理、服务治理等开箱即用
  • 传输层简洁直接transport/servertransport/client 分别提供函数式选项构造;外部 transport 实现可复用 transport/server/{endpoint,accept}transport/client/endpoint;TLS 配置构造归 security/tls
  • Proto First:框架级公共 proto 定义,通过 BSR 发布
  • 自定义 protoc 插件protoc-gen-servora-authzprotoc-gen-servora-auditprotoc-gen-servora-mapper
  • CLI 工具svr 命令行工具(GORM GEN 代码生成、OpenFGA 初始化与 model 管理)
  • 可插拔认证security/authn 接口驱动,内置 JWT 引擎与 Keycloak claims 映射
  • 细粒度授权security/authz 接口驱动,内置 OpenFGA 引擎
  • 全链路审计obs/audit 经 Kafka 投递审计事件
  • 服务治理:注册发现、配置中心(支持重载)与基础遥测

Transport 快速示例

构建 gRPC/HTTP Server
grpcSrv := transportgrpc.NewServer(
    transportgrpc.WithConfig(c.Grpc),
    transportgrpc.WithLogger(logger),
    transportgrpc.WithMiddleware(mw...),
    transportgrpc.WithServices(
        transportgrpc.Registrar(func(s *kgrpc.Server) {
            workerpb.RegisterWorkerServiceServer(s, workerSvc)
        }),
    ),
)

httpSrv := transporthttp.NewServer(
    transporthttp.WithConfig(c.Http),
    transporthttp.WithLogger(logger),
    transporthttp.WithMiddleware(mw...),
    transporthttp.WithServices(
        transporthttp.Registrar(func(s *khttp.Server) {
            masterpb.RegisterMasterServiceHTTPServer(s, masterSvc)
        }),
    ),
)
构建 Client 并发起 gRPC 调用
dialer := transportgrpc.NewDialer(
    transportgrpc.WithData(dataCfg),
    transportgrpc.WithDiscovery(discovery),
    transportgrpc.WithLogger(logger),
    transportgrpc.WithMiddleware(mw...),
)

conn, err := dialer.Dial(ctx, "worker.service")
if err != nil {
    return err
}

_, err = workerpb.NewWorkerServiceClient(conn).Hello(ctx, req)
if err != nil {
    return err
}
构建 HTTP Client
dialer := transporthttp.NewDialer(
    transporthttp.WithData(dataCfg),
    transporthttp.WithDiscovery(discovery),
    transporthttp.WithLogger(logger),
)

client, err := dialer.Dial(ctx, "master.service")
if err != nil {
    return err
}

技术栈

  • 框架:Kratos v2
  • API:Protobuf + Buf v2
  • DI:Google Wire
  • ORM:Ent(主)+ GORM GEN(并行)
  • 认证:Keycloak(OIDC)/ JWT / JWKS
  • 授权:OpenFGA
  • 存储:PostgreSQL + Redis
  • 消息:Kafka(franz-go)
  • 观测:OTel Collector / Jaeger / Loki / Prometheus / Grafana

项目结构

.
├── api/
│   ├── gen/go/                      # Go 生成代码(由 proto 生成,勿手改)
│   └── protos/                      # 框架级公共 proto(conf、pagination、authz 注解、audit 注解、mapper 注解)
├── cmd/
│   ├── svr/                         # CLI 工具(svr gen gorm / svr openfga)
│   ├── protoc-gen-servora-authz/    # AuthZ 规则生成插件
│   ├── protoc-gen-servora-audit/    # Audit 注解生成插件
│   └── protoc-gen-servora-mapper/   # 对象映射生成插件
├── core/                            # 框架横切协议 + 平台能力(bootstrap/config/registry/mapper/pagination)
├── transport/
│   ├── client/                      # 客户端 Dialer(grpc/http/middleware)+ endpoint 索引
│   └── server/                      # 服务端 NewServer(grpc/http/middleware)+ endpoint/accept
│                                    # 其中 http/ 含 cors/swagger/health 子包
├── security/                        # 认证授权与 JWT/JWKS;tls/ 提供 TLS 配置构造
├── obs/                             # 审计、日志、遥测
├── infra/                           # broker、db、k8s、redis
├── buf.yaml                         # Buf v2 workspace(公共 proto 发布到 buf.build/servora/servora)
├── buf.go.gen.yaml                  # Go 代码生成模板(含 authz / mapper / audit 等自定义插件)
├── go.mod                           # Go module: github.com/Servora-Kit/servora
└── Makefile                         # 框架构建入口

安装与使用

作为 Go 依赖
go get github.com/Servora-Kit/servora@latest
安装 CLI 工具
go install github.com/Servora-Kit/servora/cmd/svr@latest
安装自定义 protoc 插件
go install github.com/Servora-Kit/servora/cmd/protoc-gen-servora-authz@latest
go install github.com/Servora-Kit/servora/cmd/protoc-gen-servora-audit@latest
go install github.com/Servora-Kit/servora/cmd/protoc-gen-servora-mapper@latest
引用公共 Proto(BSR)

在业务仓库的 buf.yaml 中添加依赖:

deps:
  - buf.build/servora/servora

本地开发

前置要求
  • Go 1.26.1+
  • Make
  • Buf CLI
初始化开发环境
make init    # 安装 protoc 插件与 CLI 工具
make gen     # 生成 proto Go 代码
常用命令
make init          # 安装工具
make gen           # 生成所有代码(api)
make api           # 仅生成 proto Go 代码
make lint          # Go lint
make ci.lint       # CI 对齐 lint(GOWORK=off + proto lint)
make lint.proto    # Proto lint
make test          # 运行测试
make tidy          # go mod tidy + go work sync
make tag TAG=v0.x.y      # 自动打双 tag(v0.x.y + api/gen/v0.x.y)
make buf-push      # 推送 proto 到 BSR(自动使用 Git tag 作为 label)
make clean         # 清理生成代码
多仓库联合开发

框架与业务微服务采用独立仓库,本地开发时通过顶层 go.work 联合:

cd /path/to/servora-kit
# go.work 文件已配置 use 和 replace 指令
go build ./...

质量约束

  • 不要手动编辑生成代码:api/gen/go/
  • 修改 proto 后执行 make gen
  • 提交前通过 make ci.lint(避免本地 go.work 与 CI 环境不一致)
  • 推送/发版前建议额外执行 GOWORK=off go test ./...

Star History

Star History Chart

Acknowledgements

  • Thanks to all users for suggestions and feedback.
  • Thanks to all contributors and supporters in the open-source community.

Contributors

License

MIT,详见 LICENSE

Directories

Path Synopsis
api
gen module
cmd
internal/optionmerge
Package optionmerge provides shared merge logic for the three protoc-gen-servora-* plugins (authn, authz, audit).
Package optionmerge provides shared merge logic for the three protoc-gen-servora-* plugins (authn, authz, audit).
protoc-gen-servora-audit command
Command protoc-gen-servora-audit translates servora audit proto annotations into a Go file (`audit_rules.gen.go`) that exports a map of audit.CompiledRule entries consumed by the audit middleware at runtime.
Command protoc-gen-servora-audit translates servora audit proto annotations into a Go file (`audit_rules.gen.go`) that exports a map of audit.CompiledRule entries consumed by the audit middleware at runtime.
protoc-gen-servora-authn command
Command protoc-gen-servora-authn translates servora authn proto annotations into a Go file (`authn_rules.gen.go`) that the runtime can consult to decide which RPC methods are public, and which method requires which authentication schemes.
Command protoc-gen-servora-authn translates servora authn proto annotations into a Go file (`authn_rules.gen.go`) that the runtime can consult to decide which RPC methods are public, and which method requires which authentication schemes.
protoc-gen-servora-authz command
Command protoc-gen-servora-authz translates servora authz proto annotations into a Go file (`authz_rules.gen.go`) consumed by the runtime to enforce authorization on RPC methods.
Command protoc-gen-servora-authz translates servora authz proto annotations into a Go file (`authz_rules.gen.go`) consumed by the runtime to enforce authorization on RPC methods.
protoc-gen-servora-conf command
Command protoc-gen-servora-conf consumes servora.conf.v1 annotations on configuration messages and emits a companion <file>.pb.servora-conf.go that declares receiver methods bound to the generated *.pb.go types:
Command protoc-gen-servora-conf consumes servora.conf.v1 annotations on configuration messages and emits a companion <file>.pb.servora-conf.go that declares receiver methods bound to the generated *.pb.go types:
svr command
core
infra
broker
Package broker defines Servora's minimal message broker abstraction.
Package broker defines Servora's minimal message broker abstraction.
broker/kafka
Package kafka provides a franz-go based implementation of pkg/broker.
Package kafka provides a franz-go based implementation of pkg/broker.
db/clickhouse
Package clickhouse provides a framework-level ClickHouse connection helper following the Optional-init pattern established by pkg/broker/kafka.
Package clickhouse provides a framework-level ClickHouse connection helper following the Optional-init pattern established by pkg/broker/kafka.
k8s
obs
audit
Package audit provides engine-agnostic audit event emission using CloudEvents as the envelope format.
Package audit provides engine-agnostic audit event emission using CloudEvents as the envelope format.
audit/kafka
Package kafka provides a stub Auditor for Kafka-based audit event delivery.
Package kafka provides a stub Auditor for Kafka-based audit event delivery.
audit/multi
Package multi provides an Auditor that fans out events to multiple backends.
Package multi provides an Auditor that fans out events to multiple backends.
audit/noop
Package noop provides a no-op Auditor that discards all events silently.
Package noop provides a no-op Auditor that discards all events silently.
audit/stdout
Package stdout provides an Auditor that JSON-encodes CloudEvents to stdout.
Package stdout provides an Auditor that JSON-encodes CloudEvents to stdout.
security
authn
Package authn provides an engine-agnostic Kratos middleware dispatcher for authentication.
Package authn provides an engine-agnostic Kratos middleware dispatcher for authentication.
authn/apikey
Package apikey provides an API-key authentication skeleton for the engine-agnostic authn dispatcher.
Package apikey provides an API-key authentication skeleton for the engine-agnostic authn dispatcher.
authn/jwt
Package jwt provides a generic Bearer JWT authentication skeleton for the engine-agnostic authn dispatcher.
Package jwt provides a generic Bearer JWT authentication skeleton for the engine-agnostic authn dispatcher.
authn/noop
Package noop provides a no-op Authenticator that passes through without enrichment.
Package noop provides a no-op Authenticator that passes through without enrichment.
authz
Package authz provides a generic Kratos middleware for authorization.
Package authz provides a generic Kratos middleware for authorization.
authz/batch
Package batch defines the optional BatchAuthorizer sub-interface for authorization backends that support multi-check in a single round-trip.
Package batch defines the optional BatchAuthorizer sub-interface for authorization backends that support multi-check in a single round-trip.
authz/lister
Package lister defines the optional Lister sub-interface for authorization backends that can enumerate resources a subject is allowed to access.
Package lister defines the optional Lister sub-interface for authorization backends that can enumerate resources a subject is allowed to access.
authz/noop
Package noop provides a no-op Authorizer that always permits all requests.
Package noop provides a no-op Authorizer that always permits all requests.
authz/openfga
Package openfga provides an OpenFGA-based Authorizer implementation for security/authz.
Package openfga provides an OpenFGA-based Authorizer implementation for security/authz.
jwt
tls
transport
server/http/health
Package health 提供组件化的健康探针能力。
Package health 提供组件化的健康探针能力。
server/middleware
Package middleware 提供服务器中间件链构建工具。
Package middleware 提供服务器中间件链构建工具。

Jump to

Keyboard shortcuts

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