grpcx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 21 Imported by: 0

README

grpcx

A lightweight gRPC microservice framework for Go, stripped from go-zero.

Focuses on one thing: building gRPC services, with no extra baggage.

Features

  • gRPC server & client with clean lifecycle management
  • Built-in interceptors: tracing (OpenTelemetry), Prometheus metrics, timeout, panic recovery
  • Structured logging (logx)
  • YAML/JSON/TOML config loading (conf)
  • Graceful shutdown with signal handling
  • Health check & DevServer (pprof + metrics endpoint)
  • CLI tool for project scaffolding and code generation

What's removed (compared to go-zero)

REST framework, MySQL/PostgreSQL/MongoDB/Redis, message queues, etcd/K8s service discovery, P2C load balancing, circuit breaker, load shedding, HTTP gateway, MCP, JWT auth, goctl.

Quick Start

Install CLI
go install github.com/qwqzy/grpcx/cmd/grpcx@latest
Create a new project
grpcx new myservice
cd myservice
go mod tidy
go run main.go

This generates a complete project with a Ping RPC example:

myservice/
├── etc/myservice.yaml
├── internal/
│   ├── config/config.go
│   ├── logic/ping_logic.go
│   ├── server/myservice_server.go
│   └── svc/servicecontext.go
├── myservice/
│   ├── myservice.proto
│   ├── myservice.pb.go
│   └── myservice_grpc.pb.go
├── go.mod
└── main.go
Generate from existing proto
grpcx gen path/to/service.proto
Check environment
grpcx doctor

Verifies protoc, protoc-gen-go, and protoc-gen-go-grpc are installed and in PATH.

Server Config

Name: myservice.rpc
ListenOn: 0.0.0.0:8080
Mode: dev            # dev | test | pro
Timeout: 2000        # ms, 0 = no timeout
Health: true

Log:
  Mode: console

Telemetry:
  Name: myservice
  Endpoint: localhost:4317
  Sampler: 1.0

Client Config

Endpoints:
  - localhost:8080
Timeout: 2000
NonBlock: true

Architecture

grpcx/
├── config.go               # RpcServerConf / RpcClientConf
├── server.go               # gRPC server
├── client.go               # gRPC client
├── logger.go               # gRPC log adapter
├── serverinterceptors/     # Server interceptors: trace, recover, prometheus, timeout
├── clientinterceptors/     # Client interceptors: trace, prometheus, timeout
├── resolver/               # Direct endpoint resolver
├── cmd/grpcx/              # CLI tool (new, gen, doctor, version)
└── core/
    ├── conf/               # Config loading (YAML/JSON/TOML)
    ├── logx/               # Structured logging
    ├── logc/               # Context-aware logging
    ├── trace/              # OpenTelemetry tracing
    ├── metric/             # Prometheus metric helpers
    ├── proc/               # Process lifecycle & graceful shutdown
    ├── prometheus/         # Prometheus agent
    ├── devserver/          # Dev HTTP server (health + metrics + pprof)
    ├── health/             # Health check probe
    ├── encoding/           # YAML/TOML/JSON5 encoding
    ├── mapping/            # Struct tag mapping (config engine)
    └── ...                 # Other utility packages

License

MIT


grpcx

一个轻量级的 Go gRPC 微服务框架,从 go-zero 精简而来。

只做一件事:构建 gRPC 服务,没有多余的东西。

特性

  • gRPC 服务端和客户端,完整的生命周期管理
  • 内置拦截器:链路追踪(OpenTelemetry)、Prometheus 指标、超时控制、panic 恢复
  • 结构化日志(logx
  • YAML/JSON/TOML 配置加载(conf
  • 信号监听 + 优雅停机
  • 健康检查 & DevServer(pprof + metrics 端点)
  • CLI 工具:项目脚手架 & 代码生成

相比 go-zero 删掉了什么

REST 框架、MySQL/PostgreSQL/MongoDB/Redis、消息队列、etcd/K8s 服务发现、P2C 负载均衡、熔断器、自适应降载、HTTP 网关、MCP、JWT 认证、goctl。

快速开始

安装 CLI
go install github.com/qwqzy/grpcx/cmd/grpcx@latest
创建新项目
grpcx new myservice
cd myservice
go mod tidy
go run main.go

自动生成包含 Ping RPC 示例的完整项目:

myservice/
├── etc/myservice.yaml
├── internal/
│   ├── config/config.go
│   ├── logic/ping_logic.go
│   ├── server/myservice_server.go
│   └── svc/servicecontext.go
├── myservice/
│   ├── myservice.proto
│   ├── myservice.pb.go
│   └── myservice_grpc.pb.go
├── go.mod
└── main.go
从已有 proto 生成
grpcx gen path/to/service.proto
检查环境
grpcx doctor

检查 protocprotoc-gen-goprotoc-gen-go-grpc 是否已安装并在 PATH 中。

服务端配置

Name: myservice.rpc
ListenOn: 0.0.0.0:8080
Mode: dev            # dev | test | pro
Timeout: 2000        # 毫秒,0 = 不超时
Health: true

Log:
  Mode: console

Telemetry:
  Name: myservice
  Endpoint: localhost:4317
  Sampler: 1.0

客户端配置

Endpoints:
  - localhost:8080
Timeout: 2000
NonBlock: true

项目结构

grpcx/
├── config.go               # RpcServerConf / RpcClientConf
├── server.go               # gRPC 服务端
├── client.go               # gRPC 客户端
├── logger.go               # gRPC 日志适配
├── serverinterceptors/     # 服务端拦截器:trace, recover, prometheus, timeout
├── clientinterceptors/     # 客户端拦截器:trace, prometheus, timeout
├── resolver/               # 直连地址解析器
├── cmd/grpcx/              # CLI 工具(new, gen, doctor, version)
└── core/
    ├── conf/               # 配置加载(YAML/JSON/TOML)
    ├── logx/               # 结构化日志
    ├── logc/               # 带 context 的日志
    ├── trace/              # OpenTelemetry 链路追踪
    ├── metric/             # Prometheus 指标封装
    ├── proc/               # 进程生命周期 & 优雅停机
    ├── prometheus/         # Prometheus 代理
    ├── devserver/          # 开发 HTTP 服务(健康检查 + 指标 + pprof)
    ├── health/             # 健康检查探针
    ├── encoding/           # YAML/TOML/JSON5 编码
    ├── mapping/            # 结构体标签映射(配置引擎)
    └── ...                 # 其他工具包

许可证

MIT

Documentation

Index

Constants

View Source
const (
	DevMode  = "dev"
	TestMode = "test"
	ProMode  = "pro"
)

Variables

This section is empty.

Functions

func WithCallTimeout

func WithCallTimeout(timeout time.Duration) grpc.CallOption

WithCallTimeout return a call option with given timeout to make a method call.

Types

type ClientMiddlewaresConf

type ClientMiddlewaresConf struct {
	Trace      bool `json:",default=true"`
	Prometheus bool `json:",default=true"`
	Timeout    bool `json:",default=true"`
}

type ClientOption

type ClientOption func(options *clientOptions)

func WithDialOption

func WithDialOption(opt grpc.DialOption) ClientOption

WithDialOption returns a func to customize a clientOptions with given dial option.

func WithNonBlock

func WithNonBlock() ClientOption

WithNonBlock sets the dialing to be nonblock.

func WithStreamClientInterceptor

func WithStreamClientInterceptor(interceptor grpc.StreamClientInterceptor) ClientOption

WithStreamClientInterceptor returns a func to customize with given interceptor.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout returns a func to customize a clientOptions with given timeout.

func WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) ClientOption

WithTransportCredentials return a func to make the gRPC calls secured with given credentials.

func WithUnaryClientInterceptor

func WithUnaryClientInterceptor(interceptor grpc.UnaryClientInterceptor) ClientOption

WithUnaryClientInterceptor returns a func to customize with given interceptor.

type RegisterFn

type RegisterFn func(*grpc.Server)

RegisterFn defines the method to register services on grpc.Server.

type RpcClient

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

RpcClient is a gRPC client.

func MustNewClient

func MustNewClient(c RpcClientConf, options ...ClientOption) *RpcClient

MustNewClient returns a RpcClient, exits on any error.

func NewClient

func NewClient(c RpcClientConf, options ...ClientOption) (*RpcClient, error)

NewClient returns a RpcClient.

func NewClientWithTarget

func NewClientWithTarget(target string, opts ...ClientOption) (*RpcClient, error)

NewClientWithTarget returns a RpcClient with connecting to given target.

func (*RpcClient) Conn

func (rc *RpcClient) Conn() *grpc.ClientConn

Conn returns the underlying grpc.ClientConn.

type RpcClientConf

type RpcClientConf struct {
	Endpoints     []string
	Target        string        `json:",optional"`
	NonBlock      bool          `json:",default=true"`
	Timeout       int64         `json:",default=2000"`
	KeepaliveTime time.Duration `json:",optional"`
	Middlewares   ClientMiddlewaresConf
}

func (RpcClientConf) BuildTarget

func (cc RpcClientConf) BuildTarget() (string, error)

type RpcServer

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

RpcServer is a gRPC server.

func MustNewServer

func MustNewServer(c RpcServerConf, register RegisterFn) *RpcServer

MustNewServer returns a RpcServer, exits on any error.

func NewServer

func NewServer(c RpcServerConf, register RegisterFn) (*RpcServer, error)

NewServer returns a RpcServer.

func (*RpcServer) AddOptions

func (s *RpcServer) AddOptions(options ...grpc.ServerOption)

AddOptions adds given options.

func (*RpcServer) AddStreamInterceptors

func (s *RpcServer) AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor)

AddStreamInterceptors adds given stream interceptors.

func (*RpcServer) AddUnaryInterceptors

func (s *RpcServer) AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor)

AddUnaryInterceptors adds given unary interceptors.

func (*RpcServer) Start

func (s *RpcServer) Start()

Start starts the RpcServer.

func (*RpcServer) Stop

func (s *RpcServer) Stop()

Stop stops the RpcServer.

type RpcServerConf

type RpcServerConf struct {
	Name           string
	ListenOn       string
	Mode           string            `json:",default=pro,options=dev|test|pro"`
	Log            logx.LogConf      `json:",optional"`
	Telemetry      trace.Config      `json:",optional"`
	DevServer      devserver.Config  `json:",optional"`
	Shutdown       proc.ShutdownConf `json:",optional"`
	Timeout        int64             `json:",default=2000"`
	Health         bool              `json:",default=true"`
	Middlewares    ServerMiddlewaresConf
	MethodTimeouts []MethodTimeoutConf `json:",optional"`
}

func (RpcServerConf) SetUp

func (sc RpcServerConf) SetUp() error

func (RpcServerConf) Validate

func (sc RpcServerConf) Validate() error

type ServerMiddlewaresConf

type ServerMiddlewaresConf struct {
	Trace      bool `json:",default=true"`
	Recover    bool `json:",default=true"`
	Prometheus bool `json:",default=true"`
	Timeout    bool `json:",default=true"`
}

Jump to

Keyboard shortcuts

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