Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Go Zero
https://github.com/zeromicro/zero-doc
Admin
The docs for go-zero
Tokens:
38,645
Snippets:
330
Trust Score:
7.7
License:
MIT
Update:
5 months ago
Context
Chat
Benchmark
69.13
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Main Application Entry Point Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/go-queue.md This Go code snippet shows the main function for starting the application. It parses command-line flags for the configuration file and loads the configuration using `conf.MustLoad`. This is the entry point for the application's setup. ```go /** * @Description 启动文件 * @Author Mikael * @Email 13247629622@163.com * @Date 2021/1/18 12:05 * @Version 1.0 **/ package main import ( "flag" "fmt" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/service" "job/internal/config" "job/internal/handler" "job/internal/svc" "os" "os/signal" "syscall" "time" ) var configFile = flag.String("f", "etc/job.yaml", "the config file") func main() { flag.Parse() //配置 var c config.Config conf.MustLoad(*configFile, &c) ``` -------------------------------- ### Install go-zero Framework Source: https://github.com/zeromicro/zero-doc/blob/main/readme-en.md Run this command to install the go-zero framework. Ensure you are in your project directory. ```shell go get -u github.com/zeromicro/go-zero ``` -------------------------------- ### Start the Greet Service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md Run the greet service using `go run` and specify the configuration file. The server will start listening on port 8888. ```shell $ cd ~/go-zero-demo/greet $ go run greet.go -f etc/greet-api.yaml ``` -------------------------------- ### Install goctl Source: https://github.com/zeromicro/zero-doc/blob/main/readme-en.md Install the goctl command-line tool for microservice development. Ensure Go modules are enabled. ```shell GO111MODULE=on go get -u github.com/zeromicro/go-zero/tools/goctl ``` -------------------------------- ### Example proto file definition Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/rpc.md This is an example of a proto3 file defining a 'User' service with 'Login' RPC. It includes request and response messages with field definitions and comments. ```Proto syntax = "proto3"; package remote; option go_package = "remote"; message Request { // 用户名 string username = 1; // 用户密码 string password = 2; } message Response { // 用户名称 string name = 1; // 用户性别 string gender = 2; } service User { // 登录 rpc Login(Request)returns(Response); } ``` -------------------------------- ### Implement Greet Logic Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md Write the business logic for the Greet function in `greetlogic.go`. This example returns a static greeting message. ```go func (l *GreetLogic) Greet(req types.Request) (*types.Response, error) { return &types.Response{ Message: "Hello go-zero", }, nil } ``` -------------------------------- ### Routing Specification Examples Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/project/specification.md Examples of recommended routing naming conventions using lowercase words and horizontal bar combinations. ```go /user/get-info ``` ```go /user/get/info ``` ```go /user/password/change/:id ``` -------------------------------- ### Initialize Templates to Custom Path Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/template.md Example of initializing goctl templates to a specific directory using the --home flag. ```text $ goctl template init --home $HOME/template ``` -------------------------------- ### Generated UserModel Interface and Usage Example Source: https://context7.com/zeromicro/zero-doc/llms.txt Demonstrates an auto-generated UserModel interface for database operations and provides an example of how to use it for querying user data, including cache usage. It also shows initialization. ```go package model // 自动生成的 UserModel 接口 type UserModel interface { Insert(data User) (sql.Result, error) FindOne(id int64) (*User, error) FindOneByName(name string) (*User, error) // 单索引字段自动生成 FindOneByMobile(mobile string) (*User, error) Update(data User) error Delete(id int64) error } // 使用示例:通过主键查询(自动走缓存) func GetUser(ctx context.Context, model UserModel, id int64) (*User, error) { user, err := model.FindOne(id) switch err { case nil: return user, nil case sqlc.ErrNotFound: return nil, errors.New("用户不存在") default: return nil, err } } // NewUserModel 初始化(conn 为 sqlx.SqlConn,c 为 cache.CacheConf) func main() { conn := sqlx.NewMysql("user:pass@tcp(127.0.0.1:3306)/db") cacheConf := cache.CacheConf{ {Host: "127.0.0.1:6379", Type: "node"}, } userModel := NewUserModel(conn, cacheConf) user, err := userModel.FindOne(1) _ = user _ = err } ``` -------------------------------- ### Create User RPC Directory Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Navigate to the user RPC directory to start building your service. ```shell $ cd ~/go-zero-demo/mall $ mkdir -p user/rpc && cd user/rpc ``` -------------------------------- ### zRPC Server Example Source: https://context7.com/zeromicro/zero-doc/llms.txt This Go code sets up a basic zRPC server using go-zero. It includes service registration with etcd and handles incoming RPC requests. Configuration is loaded from a YAML file. ```go // ===== 服务端 ===== package main import ( "context" "flag" "log" "example/zrpc/pb" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/zrpc" "google.golang.org/grpc" ) // hello.yaml 配置: // Name: hello.rpc // ListenOn: 127.0.0.1:9090 // Etcd: // Hosts: [127.0.0.1:2379] // Key: hello.rpc type Config struct{ zrpc.RpcServerConf } type Hello struct{} func (h *Hello) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "hello " + in.Name}, nil } func main() { var cfg Config conf.MustLoad("hello.yaml", &cfg) srv, err := zrpc.NewServer(cfg.RpcServerConf, func(s *grpc.Server) { pb.RegisterGreeterServer(s, &Hello{}) }) if err != nil { log.Fatal(err) } srv.Start() } ``` -------------------------------- ### Implement GetUser Logic Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Populate the business logic for the `GetUser` RPC method. This example returns hardcoded user data. ```go package logic import ( "context" "go-zero-demo/mall/user/rpc/internal/svc" "go-zero-demo/mall/user/rpc/user" "github.com/zeromicro/go-zero/core/logx" ) type GetUserLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLogic { return &GetUserLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } func (l *GetUserLogic) GetUser(in *user.IdRequest) (*user.UserResponse, error) { return &user.UserResponse{ Id: "1", Name: "test", }, nil } ``` -------------------------------- ### Start etcd Service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Ensure etcd is running before starting your RPC service. Refer to the etcd installation tutorial if needed. ```shell $ etcd ``` -------------------------------- ### Fx From Function Example Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/fx.md Illustrates how to construct a stream using the Fx From function, which takes a generate function to populate a channel. The generated data is then returned as a Stream. ```go s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} fx.From(func(source chan<- interface{}) { for _, v := range s { source <- v } }) ``` -------------------------------- ### Basic Fx Stream Processing Example Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/fx.md Demonstrates a basic stream processing pipeline using Fx, including input, filtering, and output. The inputStream simulates data generation, while outputStream processes it using From, Walk, Filter, and ForEach. ```go package main import ( "fmt" "os" "os/signal" "syscall" "time" "github.com/zeromicro/go-zero/core/fx" ) func main() { ch := make(chan int) go inputStream(ch) go outputStream(ch) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGTERM, syscall.SIGINT) <-c } func inputStream(ch chan int) { count := 0 for { ch <- count time.Sleep(time.Millisecond * 500) count++ } } func outputStream(ch chan int) { fx.From(func(source chan<- interface{}) { for c := range ch { source <- c } }).Walk(func(item interface{}, pipe chan<- interface{}) { count := item.(int) pipe <- count }).Filter(func(item interface{}) bool { itemInt := item.(int) if itemInt%2 == 0 { return true } return false }).ForEach(func(item interface{}) { fmt.Println(item) }) } ``` -------------------------------- ### Start User RPC Service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Run your user RPC service using the go run command and specify the configuration file. ```shell $ go run user.go -f etc/user.yaml ``` -------------------------------- ### Generate RPC with Custom Templates Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/template.md Example of generating an RPC service using templates from a specified directory. ```text $ goctl rpc new greet --home $HOME/template ``` -------------------------------- ### zRPC Client Example with Interceptor Source: https://context7.com/zeromicro/zero-doc/llms.txt This Go code demonstrates how to create a zRPC client using go-zero, including service discovery via etcd. It also shows how to add a custom interceptor for logging or other pre/post-call logic. ```go // ===== 客户端 ===== package main import ( "context" "log" "example/zrpc/pb" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/zrpc" ) func main() { // 基于 etcd 服务发现的客户端 client := zrpc.MustNewClient(zrpc.RpcClientConf{ Etcd: discov.EtcdConf{ Hosts: []string{"127.0.0.1:2379"}, Key: "hello.rpc", }, }) conn := client.Conn() greeter := pb.NewGreeterClient(conn) reply, err := greeter.SayHello(context.Background(), &pb.HelloRequest{Name: "go-zero"}) if err != nil { log.Fatal(err) } log.Println(reply.Message) // 输出: hello go-zero // 添加自定义客户端拦截器 client.(*zrpc.RpcClient).AddInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { log.Printf("调用方法: %s", method) return invoker(ctx, method, req, reply, cc, opts...) }) } ``` -------------------------------- ### Consumer Logic Start Method Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/go-queue.md This Go method starts a consumer that processes messages from the queue. It uses `threading.GoSafe` for concurrent execution and defines a callback function to handle incoming message bodies. The consumer relies on `l.svcCtx.Consumer.Consume` for message retrieval. ```go /** * @Description 消费者任务 * @Author Mikael * @Email 13247629622@163.com * @Date 2021/1/18 12:05 * @Version 1.0 **/ package logic import ( "context" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/threading" "job/internal/svc" ) type Consumer struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewConsumerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Consumer { return &Consumer{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } func (l *Consumer)Start() { logx.Infof("start consumer \n") threading.GoSafe(func() { l.svcCtx.Consumer.Consume(func(body []byte) { logx.Infof("consumer job %s \n" ,string(body)) }) }) } func (l *Consumer)Stop() { logx.Infof("stop consumer \n") } ``` -------------------------------- ### Demonstrate go-zero Model Layer Cache Usage Source: https://context7.com/zeromicro/zero-doc/llms.txt This example shows how to use a go-zero generated UserModel with integrated cache. It covers FindOne, Update, and Delete operations, highlighting the automatic cache handling for cache penetration,击穿, and avalanche. ```go package main import ( "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/sqlc" "github.com/zeromicro/go-zero/core/stores/sqlx" ) // goctl 生成的 Model 使用示例 func demonstrateCache() { conn := sqlx.NewMysql("root:pass@tcp(127.0.0.1:3306)/test") // 多 Redis 节点防雪崩(分布式缓存配置) cacheConf := cache.CacheConf{ {Host: "127.0.0.1:6379", Type: "node", Weight: 100}, {Host: "127.0.0.1:6380", Type: "node", Weight: 100}, } model := NewUserModel(conn, cacheConf) // FindOne 自动走缓存(缓存键: "cache#User#id#1") // 1. 查缓存 -> 命中则返回 // 2. 未命中 -> SingleFlight 保证只有一个请求打到 DB // 3. DB 返回 -> 写入缓存(过期时间带随机抖动 ±5%,防雪崩) // 4. DB 返回空 -> 写入占位符(防穿透,1分钟过期) user, err := model.FindOne(1) _ = user _ = err // Update 自动删除主键缓存("先更新DB,再删缓存"策略) err = model.Update(User{Id: 1, Name: "new name"}) _ = err // Delete 自动删除所有相关缓存键 err = model.Delete(1) _ = err } // 缓存监控统计日志示例(框架自动输出): // {"@timestamp":"...","level":"stat","content":" // cache(user) - requests: 5057, accepts: 5044 (99.7%), db: 13"} // 命中率 99.7% = DB 压力降低 ~3个数量级 ``` -------------------------------- ### Producer Logic Start Method Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/go-queue.md This Go method starts a producer that sends delayed messages to beanstalkd. It uses `threading.GoSafe` for concurrent execution and iterates to send multiple messages with a delay. Ensure beanstalkd is running and accessible. ```go /** * @Description 生产者任务 * @Author Mikael * @Email 13247629622@163.com * @Date 2021/1/18 12:05 * @Version 1.0 **/ package logic import ( "context" "github.com/zeromicro/go-queue/dq" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/threading" "job/internal/svc" "strconv" "time" ) type Producer struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewProducerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Producer { return &Producer{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } func (l *Producer)Start() { logx.Infof("start Producer \n") threading.GoSafe(func() { producer := dq.NewProducer([]dq.Beanstalk{ { Endpoint: "localhost:7771", Tube: "tube1", }, { Endpoint: "localhost:7772", Tube: "tube2", }, }) for i := 1000; i < 1005; i++ { _, err := producer.Delay([]byte(strconv.Itoa(i)), time.Second * 1) if err != nil { logx.Error(err) } } }) } func (l *Producer)Stop() { logx.Infof("stop Producer \n") } ``` -------------------------------- ### Fx Group Function Example Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/fx.md Demonstrates the Group function for partitioning stream items into groups based on a user-defined key. Items with the same key are collected into slices and sent to the output channel. ```go ss := []string{"golang", "google", "php", "python", "java", "c++"} fx.From(func(source chan<- interface{}) { for _, s := range ss { source <- s } }).Group(func(item interface{}) interface{} { if strings.HasPrefix(item.(string), "g") { return "g" } else if strings.HasPrefix(item.(string), "p") { return "p" } return "" }).ForEach(func(item interface{}) { fmt.Println(item) }) ``` -------------------------------- ### Take Method Implementation for Cache Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/redis-cache.md Implements the core cache retrieval logic. It first tries to get data from the cache. If not found, it uses a provided query function to fetch data from the database and then sets it in the cache. ```go func (c cacheNode) Take(v interface{}, key string, query func(v interface{}) error) error { return c.doTake(v, key, query, func(v interface{}) error { return c.SetCache(key, v) }) } ``` -------------------------------- ### Initialize go-zero Demo Project Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/concept.md Use these commands to create and initialize a new go-zero-demo project directory in your home directory. ```shell cd ~ mkdir go-zero-demo&&cd go-zero-demo go mod init go-zero-demo ``` -------------------------------- ### Test the microservice with curl Source: https://github.com/zeromicro/zero-doc/blob/main/readme-en.md Send a request to the running microservice using curl to verify its functionality. The example uses a GET request to a defined endpoint. ```shell curl -i http://localhost:8888/greet/from/you ``` -------------------------------- ### Basic Logx Initialization and Usage Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/logx.md Demonstrates how to initialize Logx from a configuration file and use its basic logging functions like Info, Infof, Error, and Errorf. Remember to close the logs when the application exits. ```go var c logx.LogConf // 从 yaml 文件中 初始化配置 conf.MustLoad("config.yaml", &c) // logx 根据配置初始化 logx.MustSetup(c) logx.Info("This is info!") logx.Infof("This is %s!", "info") logx.Error("This is error!") logx.Errorf("this is %s!", "error") logx.Close() ``` -------------------------------- ### Logx Initialization with Configuration Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/logx.md Initializes Logx using a provided LogConf object. If no configuration is provided, Logx will use its default settings. ```go logx.MustSetUp(c) ``` -------------------------------- ### goctl rpc proto command help Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/rpc.md Displays the help information for the 'goctl rpc proto' command, outlining its usage, available options, and parameter descriptions. ```Bash goctl rpc proto -h ``` -------------------------------- ### Access the Greet Service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md Send a GET request to the service endpoint using `curl`. The service responds with a JSON object containing the greeting message. ```shell $ curl -i -X GET \ http://localhost:8888/from/you ``` -------------------------------- ### Redis Cache Configuration Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/project/config.md Configures Redis cache clusters, including node weights. Supports defining multiple nodes for a distributed cache setup. ```go ClusterConf []NodeConf NodeConf struct { redis.RedisConf Weight int `json:",default=100"` // weight } ``` -------------------------------- ### Create New Greet Service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md Use `goctl` to generate a new greet service. This command initializes the project structure and basic files. ```shell $ cd ~/go-zero-demo $ go mod init go-zero-demo $ goctl api new greet Done. ``` -------------------------------- ### Fx Filter Function Example Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/fx.md Shows how to use the Filter function to selectively keep items from a stream based on a provided FilterFunc. Items for which the function returns true are retained. ```go s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} fx.From(func(source chan<- interface{}) { for _, v := range s { source <- v } }).Filter(func(item interface{}) bool { if item.(int)%2 == 0 { return true } return false }) ``` -------------------------------- ### Data Processing with mr.MapReduce Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/other-component/mapreduce.md Utilize mr.MapReduce for complex data processing pipelines involving mapping, filtering, and reducing steps. This example demonstrates checking the legality of user IDs concurrently. ```go func checkLegal(uids []int64) ([]int64, error) { r, err := mr.MapReduce(func(source chan<- interface{}) { for _, uid := range uids { source <- uid } }, func(item interface{}, writer mr.Writer, cancel func(error)) { uid := item.(int64) ok, err := check(uid) if err != nil { cancel(err) } if ok { writer.Write(uid) } }, func(pipe <-chan interface{}, writer mr.Writer, cancel func(error)) { var uids []int64 for p := range pipe { uids = append(uids, p.(int64)) } writer.Write(uids) }) if err != nil { return nil, err } return r.([]int64), nil } func check(uid int64) (bool, error) { // do something check user legal time.Sleep(time.Millisecond * 20) return true, nil } ``` -------------------------------- ### Generate greet RPC service Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/rpc.md Use this command to quickly generate a new RPC service named 'greet'. The command scaffolds the basic project structure, including configuration files, proto definitions, and server/client code. ```Bash goctl rpc new greet ``` -------------------------------- ### DqConf Configuration Example Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/go-queue.md This YAML configuration defines the settings for the dq mode, including beanstalkd endpoints and tubes, as well as Redis connection details. Ensure beanstalkd and Redis are accessible at the specified endpoints. ```yaml Name: job Log: ServiceName: job Level: info #dq依赖Beanstalks、redis ,Beanstalks配置、redis配置 DqConf: Beanstalks: - Endpoint: 127.0.0.1:7771 Tube: tube1 - Endpoint: 127.0.0.1:7772 Tube: tube2 Redis: Host: 127.0.0.1:6379 Type: node ``` -------------------------------- ### Run the generated Go server Source: https://github.com/zeromicro/zero-doc/blob/main/readme-en.md Navigate to the generated project directory and run the server using the provided configuration file. The service defaults to port 8888. ```shell cd greet go run greet.go -f etc/greet-api.yaml ``` -------------------------------- ### Configuring Balancer with Client Option Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/zrpc.md Demonstrates how to specify which balancer to use when creating a new gRPC client. The `grpc.WithBalancerName` option is passed during client initialization. ```go func NewClient(target string, opts ...ClientOption) (*client, error) { var cli client opts = append(opts, WithDialOption(grpc.WithBalancerName(p2c.Name))) if err := cli.dial(target, opts...); err != nil { return nil, err } return &cli, nil } ``` -------------------------------- ### Goctl Template CLI Help Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/template.md Displays the available commands and options for operating on goctl templates. ```text NAME: goctl template - template operation USAGE: goctl template command [command options] [arguments...] COMMANDS: init initialize the all templates(force update) clean clean the all cache templates update update template of the target category to the latest revert revert the target template to the latest OPTIONS: --help, -h show help ``` -------------------------------- ### Initialize Goctl Templates Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/template.md Initializes all goctl templates, forcing an update. Use the --home option to specify a custom template directory. ```text NAME: goctl template init - initialize the all templates(force update) USAGE: goctl template init [command options] [arguments...] OPTIONS: --home value the goctl home path of the template ``` -------------------------------- ### Stream Processing with fx: Filtering and Output Source: https://context7.com/zeromicro/zero-doc/llms.txt Demonstrates basic stream processing using `fx.From` to create a stream from a slice, followed by `Filter` to keep even numbers and `ForEach` to print them. This pattern is useful for transforming and processing collections. ```go package main import ( "fmt" "strings" "github.com/zeromicro/go-zero/core/fx" ) func main() { // 基础流处理:过滤偶数并输出 s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} fx.From(func(source chan<- interface{}) { for _, v := range s { source <- v } }).Filter(func(item interface{}) bool { return item.(int)%2 == 0 // 保留偶数 }).ForEach(func(item interface{}) { fmt.Println(item) // 输出: 0 2 4 6 8 }) // 去重:保留唯一元素 fx.Just(1, 2, 2, 3, 3, 4).Distinct(func(item interface{}) interface{} { return item }).ForEach(func(item interface{}) { fmt.Println(item) // 输出: 1 2 3 4 }) // 分组:按首字母分组 ss := []string{"golang", "google", "php", "python", "java"} fx.From(func(source chan<- interface{}) { for _, s := range ss { source <- s } }).Group(func(item interface{}) interface{} { s := item.(string) if strings.HasPrefix(s, "g") { return "g" } else if strings.HasPrefix(s, "p") { return "p" } return "other" }).ForEach(func(item interface{}) { fmt.Println(item) // 分组后的 slice }) // Walk:并发转换(默认 16 并发),将字符串转大写 fx.Just("aaa", "bbb", "ccc").Walk(func(item interface{}, pipe chan<- interface{}) { pipe <- strings.ToUpper(item.(string)) }).ForEach(func(item interface{}) { fmt.Println(item) // 输出: AAA BBB CCC }) // Reverse + Head/Tail:反转后取前 N 个 fx.Just(1, 2, 3, 4, 5).Reverse().Head(3).ForEach(func(item interface{}) { fmt.Println(item) // 输出: 5 4 3 }) // 并发执行多个独立任务(无返回值) fx.Parallel(func() { userRPC() // 并发调用依赖 1 }, func() { accountRPC() // 并发调用依赖 2 }, func() { orderRPC() // 并发调用依赖 3 }) } ``` -------------------------------- ### Implement Adaptive Circuit Breaker in Go Source: https://context7.com/zeromicro/zero-doc/llms.txt Use the breaker.NewBreaker function to get a circuit breaker instance. The Do method executes a function and handles potential errors, returning ErrServiceUnavailable if the circuit is open. Use DoWithFallback to provide a fallback mechanism when the circuit breaker is open. ```go package main import ( "github.com/zeromicro/go-zero/core/breaker" ) func callDownstreamService(name string, req interface{}) error { // 获取熔断器实例(按服务名隔离) b := breaker.NewBreaker(breaker.WithName(name)) err := b.Do(func() error { // 执行实际调用 return httpClient.Call(req) }) // 熔断触发时返回:circuit breaker is open if err == breaker.ErrServiceUnavailable { // 降级处理:返回缓存结果或默认值 return fallbackResponse() } return err } // 带 fallback 的熔断调用 func callWithFallback(req interface{}) (interface{}, error) { b := breaker.NewBreaker() var result interface{} err := b.DoWithFallback(func() error { var err error result, err = downstreamRPC(req) return err }, func(err error) error { // 熔断开路时的降级逻辑 result = defaultResponse() return nil }) return result, err } // Google SRE 自适应熔断算法核心: // dropRatio = max(0, (total - protection - k*accepts) / (total + 1)) // 其中 k 默认为 1.5(越小越激进,越大越宽松) // 当随机数 < dropRatio 时触发熔断,直接返回 ErrServiceUnavailable // zRPC 中熔断器自动集成,无需手动配置: // func BreakerInterceptor(ctx, method, req, reply, cc, invoker, opts) error { // breakerName := path.Join(cc.Target(), method) // return breaker.DoWithAcceptable(breakerName, func() error { // return invoker(ctx, method, req, reply, cc, opts...) // }, codes.Acceptable) // } ``` -------------------------------- ### Define User Proto File Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Define the user RPC service and its methods in a proto file. Ensure `go_package` is set for newer protoc-gen-go versions. ```protobuf syntax = "proto3"; package user; //protoc-gen-go version greater than 1.4.0, proto file need to add go_package, otherwise it can not be generated option go_package = "./user"; message IdRequest { string id = 1; } message UserResponse { // 用户id string id = 1; // 用户名称 string name = 2; // 用户性别 string gender = 3; } service User { rpc getUser(IdRequest) returns(UserResponse); } ``` -------------------------------- ### logx Structured Logging Configuration and Usage Source: https://context7.com/zeromicro/zero-doc/llms.txt This Go code initializes and uses the go-zero logx component for structured logging. It covers configuration options like log level, output mode (file/console), and demonstrates basic logging, slow query logging, and context-aware logging. ```go package main import ( "context" "time" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/timex" ) func main() { // 初始化配置(也可从 yaml 加载) logx.MustSetUp(logx.LogConf{ ServiceName: "order-service", Mode: "file", // console | file | volume(k8s) Path: "./logs", // 日志输出路径 Level: "info", // info | error | severe Compress: true, // 日志文件是否压缩 KeepDays: 7, // 日志保留天数 StackCooldownMillis: 100, }) // 基本日志打印(异步写入) logx.Info("服务启动成功") logx.Infof("监听端口: %d", 8888) logx.Error("发生错误") logx.Errorf("数据库连接失败: %v", "timeout") // 打印慢查询耗时(输出 duration 字段) startTime := timex.Now() // ... 执行数据库查询 ... duration := timex.Since(startTime) if duration > time.Millisecond*500 { logx.WithDuration(duration).Slowf("[SQL] 慢查询: select * from users") } else { logx.WithDuration(duration).Infof("[SQL] 查询完成") } // 输出:{"@timestamp":"...","level":"slow","duration":"520ms","content":"[SQL] 慢查询..."} // 链路追踪日志(注入 traceId / spanId) ctx := context.Background() logx.WithContext(ctx).Info("处理请求") // 收集系统 log 到 logx logx.CollectSysLog() // 优雅关闭(防止日志丢失,必须调用) proc.AddShutdownListener(func() { logx.Close() }) } // 动态调整日志级别 logx.SetLevel(logx.ErrorLevel) // 只输出 error/slow/stack 级别 ``` -------------------------------- ### Generate HTTP API Service Code with goctl api Source: https://context7.com/zeromicro/zero-doc/llms.txt Use `goctl api new` to quickly create a new API service with a complete directory structure. After filling in business logic, start the service and access the API. You can also generate Go code from an existing .api file or generate client code for other languages. ```shell # 1. 快速创建一个新的 API 服务(生成完整目录结构) $ mkdir go-zero-demo && cd go-zero-demo $ go mod init go-zero-demo $ goctl api new greet # 生成的目录结构: # greet/ # ├── etc/greet-api.yaml # 配置文件 # ├── greet.api # API 描述文件 # ├── greet.go # 入口文件 # └── internal/ # ├── config/config.go # ├── handler/greethandler.go # ├── handler/routes.go # ├── logic/greetlogic.go # ├── svc/servicecontext.go # └── types/types.go # 2. 在 greetlogic.go 中填写业务逻辑 # func (l *GreetLogic) Greet(req types.Request) (*types.Response, error) { # return &types.Response{Message: "Hello go-zero"}, nil # } # 3. 启动服务 $ cd greet && go run greet.go -f etc/greet-api.yaml # Starting server at 0.0.0.0:8888... # 4. 访问接口 $ curl -i -X GET http://localhost:8888/from/you # HTTP/1.1 200 OK # Content-Type: application/json # {"message":"Hello go-zero"} # 5. 从已有 .api 文件生成 Go 代码(带文件命名风格控制) $ goctl api go -api user.api -dir . -style gozero # 6. 生成其他语言客户端代码 $ goctl api java -api greet.api -dir greet $ goctl api ts -api greet.api -dir greet $ goctl api dart -api greet.api -dir greet ``` -------------------------------- ### goctl rpc proto command options Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/rpc.md Lists the available options for the 'goctl rpc proto' command, including source proto file path, import paths, target directory, and style formatting. ```Bash OPTIONS: --src value, -s value the file path of the proto source file --proto_path value, -I value native command of protoc, specify the directory in which to search for imports. [optional] --dir value, -d value the target path of the code --style value the file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md] --idea whether the command execution environment is from idea plugin. [optional] ``` -------------------------------- ### zRPC Server Implementation Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/zrpc.md A basic zRPC server implementation that registers a Greeter service and handles SayHello requests. ```go package main import ( "context" "flag" "log" "example/zrpc/pb" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/zrpc" "google.golang.org/grpc" ) type Config struct { zrpc.RpcServerConf } var cfgFile = flag.String("f", "./hello.yaml", "cfg file") func main() { flag.Parse() var cfg Config conf.MustLoad(*cfgFile, &cfg) srv, err := zrpc.NewServer(cfg.RpcServerConf, func(s *grpc.Server) { pb.RegisterGreeterServer(s, &Hello{}) }) if err != nil { log.Fatal(err) } srv.Start() } type Hello struct{} func (h *Hello) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "hello " + in.Name}, nil } ``` -------------------------------- ### Inspect Service Structure Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md Navigate into the generated service directory and use `tree` to view the file and directory structure. ```shell $ cd greet $ tree ``` -------------------------------- ### Define API with goctl Source: https://github.com/zeromicro/zero-doc/blob/main/readme-en.md Create an API definition file (e.g., greet.api) using goctl's syntax. This file describes the request, response, and service endpoints. Parameters are automatically validated. ```go type Request { Name string `path:"name,options=you|me"` // parameters are auto validated } type Response { Message string `json:"message"` } service greet-api { @server( handler: GreetHandler ) get /greet/from/:name(Request) returns (Response); } ``` -------------------------------- ### Greet Service Directory Structure Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-api.md The generated service includes directories for configuration, handlers, logic, service context, and types. ```text . ├── etc │ └── greet-api.yaml ├── greet.api ├── greet.go └── internal ├── config │ └── config.go ├── handler │ ├── greethandler.go │ └── routes.go ├── logic │ └── greetlogic.go ├── svc │ └── servicecontext.go └── types └── types.go ``` -------------------------------- ### Show goctl api command help Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/api.md Displays the main help information for the `goctl api` command, listing available subcommands and global options. ```shell $ goctl api -h ``` -------------------------------- ### P2C Load Balancer Choose Method Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/zrpc.md Compares two selected nodes and determines which one to use based on their current load. It also includes logic to 'force pick' a node if it hasn't been picked recently, helping to ensure better distribution. ```go func (p *p2cPicker) choose(c1, c2 *subConn) *subConn { start := int64(timex.Now()) if c2 == nil { atomic.StoreInt64(&c1.pick, start) return c1 } if c1.load() > c2.load() { c1, c2 = c2, c1 } pick := atomic.LoadInt64(&c2.pick) if start-pick > forcePick && atomic.CompareAndSwapInt64(&c2.pick, pick, start) { return c2 } else { atomic.StoreInt64(&c1.pick, start) return c1 } } ``` -------------------------------- ### Show goctl api go subcommand help Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/api.md Displays detailed help for the `goctl api go` subcommand, which is used to generate Go API service files. ```shell $ goctl api go -h ``` -------------------------------- ### goctl rpc proto command usage Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/build-tool/rpc.md Shows the command syntax for generating RPC services from proto files. It details the main command and its arguments. ```Bash goctl rpc proto [command options] [arguments...] ``` -------------------------------- ### Build p2cPicker from PickerBuildInfo Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/component/balance.md Implements the balancer.Picker interface's Build method. It processes node information and constructs a p2cPicker instance, initializing it with connection details and a random number generator. ```go func (b *p2cPickerBuilder) Build(info base.PickerBuildInfo) balancer.Picker { ...... var conns []*subConn for conn, connInfo := range readySCs { conns = append(conns, &subConn{ addr: connInfo.Address, conn: conn, success: initSuccess, }) } return &p2cPicker{ conns: conns, r: rand.New(rand.NewSource(time.Now().UnixNano())), stamp: syncx.NewAtomicDuration(), } } ``` -------------------------------- ### Configure RPC Server Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/quick-start/build-rpc.md Define the configuration for your RPC server, including server settings and etcd integration. ```go package config import ( "github.com/zeromicro/go-zero/zrpc" ) type Config struct { zrpc.RpcServerConf } ``` -------------------------------- ### Generate Go Code from Proto Source: https://github.com/zeromicro/zero-doc/blob/main/website/i18n/en/docusaurus-plugin-content-docs/current/extension/zrpc.md Command to generate Go language bindings from a Protocol Buffers definition file. ```bash protoc --go_out=plugins=grpc:. hello.proto ```