Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Go Zero
https://github.com/zeromicro/go-zero
Admin
A cloud-native Go microservices framework with cli tool for productivity.
Tokens:
21,460
Snippets:
291
Trust Score:
7.7
License:
MIT
Update:
1 month ago
Context
Chat
Benchmark
57.76
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Create Your Server Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example Go code to create and start an MCP server with a 'greet' tool. ```go package main import ( "context" "log" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/mcp" ) type GreetArgs struct { Name string `json:"name" jsonschema:"description=Name of the person to greet" } func main() { // Load configuration var c mcp.McpConf conf.MustLoad("config.yaml", &c) // Create MCP server server := mcp.NewMcpServer(c) // Register a tool with automatic schema generation using the SDK directly tool := &mcp.Tool{ Name: "greet", Description: "Greet someone by name", } handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Hello, " + args.Name + "!"}, }, }, nil, nil } // Register tool with type-safe generics - no need to import official SDK mcp.AddTool(server, tool, handler) // Start server defer server.Stop() server.Start() } ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/zeromicro/go-zero/blob/master/core/conf/readme.md An example of a TOML configuration file, demonstrating optional fields and environment variable usage. ```toml # most fields are optional or have default values port = 8_080 logMode = "console" # you can use env settings maxBytes = "${MAX_BYTES}" ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/zeromicro/go-zero/blob/master/core/conf/readme.md An example of a YAML configuration file, showing optional fields and environment variable usage. ```yaml # most fields are optional or have default values port: 8080 logMode: console # you can use env settings maxBytes: ${MAX_BYTES} ``` -------------------------------- ### Installation Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Install go-zero using go get. ```shell go get -u github.com/tal-tech/go-zero ``` -------------------------------- ### Install and verify goctl Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Install the goctl tool and verify the installation by checking its version. ```bash go install github.com/zeromicro/go-zero/tools/goctl@latest goctl --version ``` -------------------------------- ### Installation Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Install the go-zero package. The MCP SDK is a transitive dependency. ```bash go get github.com/zeromicro/go-zero ``` -------------------------------- ### Install goctl tool Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Install the goctl tool for API generation. ```shell GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/tal-tech/go-zero/tools/goctl ``` -------------------------------- ### Loading Configuration Source: https://github.com/zeromicro/go-zero/blob/master/core/conf/readme.md Examples of loading configuration from a file, with options for error handling and enabling environment variable reading. ```go // exit on error var config RestfulConf conf.MustLoad(configFile, &config) // or handle the error on your own var config RestfulConf if err := conf.Load(configFile, &config); err != nil { log.Fatal(err) } // enable reading from environments var config RestfulConf conf.MustLoad(configFile, &config, conf.UseEnv()) ``` -------------------------------- ### Install protoc plugins and generate RPC code Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/README.md Install the necessary Go plugins for protobuf and gRPC, then execute goctl rpc to generate code from a proto file. ```bash # Install protoc plugins go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest # Try the basic example cd 01-basic mkdir -p output && cd output && go mod init example.com/demo && cd .. goctl rpc protoc greeter.proto \ --go_out=output --go-grpc_out=output --zrpc_out=output \ --go_opt=module=example.com/demo --go-grpc_opt=module=example.com/demo \ --module=example.com/demo -I . ``` -------------------------------- ### Run the generated service Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Commands to initialize dependencies and start the generated Go service. ```shell cd greet go mod tidy go run greet.go -f etc/greet-api.yaml ``` -------------------------------- ### Install goctl tool Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Commands to install the goctl CLI tool via Go, Homebrew, or Docker. ```shell # for Go go install github.com/zeromicro/go-zero/tools/goctl@latest # For Mac brew install goctl # docker for all platforms docker pull kevinwan/goctl # run goctl docker run --rm -it -v `pwd`:/app kevinwan/goctl --help ``` -------------------------------- ### Curl request example Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Example curl request to the running server. ```shell curl -i http://localhost:8888/greet/from/you ``` -------------------------------- ### Define API file (greet.api) Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Example of an API definition file for a greet service. ```go type Request { Name string `path:"name,options=you|me"` // 框架自动验证请求参数是否合法 } type Response { Message string `json:"message"` } service greet-api { @server( handler: GreetHandler ) get /greet/from/:name(Request) returns (Response); } ``` -------------------------------- ### Install go-zero dependency Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Run this command within your project directory to add the go-zero package. ```shell go get -u github.com/zeromicro/go-zero ``` -------------------------------- ### Install protoc plugins Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Required dependencies for generating Go code from proto files. ```bash # Install protoc plugins go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` -------------------------------- ### Gateway Configuration Example Source: https://github.com/zeromicro/go-zero/blob/master/gateway/readme.md An example YAML configuration file for the go-zero gateway, showing upstream service definitions and mappings. ```yaml Name: demo-gateway Host: localhost Port: 8888 Upstreams: - Grpc: Etcd: Hosts: - localhost:2379 Key: hello.rpc # protoset mode ProtoSets: - hello.pb # Mappings can also be written in proto options Mappings: - Method: get Path: /pingHello/:ping RpcPath: hello.Hello/Ping - Grpc: Endpoints: - localhost:8081 # reflection mode, no ProtoSet settings Mappings: - Method: post Path: /pingWorld RpcPath: world.World/Ping ``` -------------------------------- ### Configuration Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example configuration file for the MCP server. ```yaml name: my-mcp-server host: localhost port: 8080 mcp: name: my-mcp-server version: 1.0.0 useStreamable: false # Use SSE transport (default), set to true for Streamable HTTP sseEndpoint: /sse messageEndpoint: /message sseTimeout: 24h messageTimeout: 30s cors: - http://localhost:3000 ``` -------------------------------- ### Updated configuration structure example Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md Example of the updated MCP server configuration in YAML format. ```yaml mcp: name: my-server version: 1.0.0 useStreamable: false # false = SSE (2024-11-05), true = Streamable HTTP (2025-03-26) sseEndpoint: /sse messageEndpoint: /message sseTimeout: 24h messageTimeout: 30s cors: - http://localhost:3000 ``` -------------------------------- ### Example Migration: Before Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md Code snippet showing the old way of registering a tool before migrating to the official SDK. ```go server := mcp.NewMcpServer(c) tool := &mcp.Tool{Name: "greet", Description: "Greet"} handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{ Content: []mcp.Content{&mcp.TextContent{Text: "Hello"}}, }, nil, nil } if err := server.AddTool(tool, handler); err != nil { log.Fatal(err) } ``` -------------------------------- ### Example Migration: After Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md Code snippet showing the new way of registering a tool after migrating to the official SDK. ```go import sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" server := mcp.NewMcpServer(c) tool := &mcp.Tool{Name: "greet", Description: "Greet"} handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{ Content: []mcp.Content{&mcp.TextContent{Text: "Hello"}}, }, nil, nil } // Use SDK directly - no error return sdkmcp.AddTool(server.Server(), tool, handler) ``` -------------------------------- ### Adding Prompts Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example Go code for adding a 'code-review' prompt. ```go prompt := &mcp.Prompt{ Name: "code-review", Description: "Review code for best practices", } handler := func(ctx context.Context, req *sdkmcp.GetPromptRequest, args map[string]string) (*mcp.GetPromptResult, error) { code := args["code"] language := args["language"] return &mcp.GetPromptResult{ Messages: []mcp.PromptMessage{ { Role: "user", Content: &mcp.TextContent{ Text: fmt.Sprintf("Please review this %s code:\n\n%s", language, code), }, }, }, }, nil } server.AddPrompt(prompt, handler) ``` -------------------------------- ### Correct Single Line Comment Example Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Examples of correctly formatted single-line comments. ```api // doc // comment ``` -------------------------------- ### Correct Java-style Doc Comment Example Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Examples of correctly formatted Java-style documentation comments. ```api /** * java-style doc */ ``` -------------------------------- ### Adding Resources Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example of how to define and add a resource to the MCP server, including a handler function for reading the resource. ```go resource := &mcp.Resource{ URI: "file:///docs/readme.md", Name: "README", Description: "Project documentation", MimeType: "text/markdown", } handler := func(ctx context.Context, req *sdkmcp.ReadResourceRequest, uri string) (*mcp.ReadResourceResult, error) { content, err := os.ReadFile("README.md") if err != nil { return nil, err } return &mcp.ReadResourceResult{ Contents: []mcp.ResourceContents{ { URI: uri, MimeType: "text/markdown", Text: string(content), }, }, }, nil } server.AddResource(resource, handler) ``` -------------------------------- ### Adding Tools Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example Go code for adding a 'calculate' tool with automatic JSON schema generation. ```go type CalculateArgs struct { Operation string `json:"operation" jsonschema:"enum=add,enum=subtract,enum=multiply,enum=divide" A float64 `json:"a" jsonschema:"description=First number" B float64 `json:"b" jsonschema:"description=Second number" } tool := &mcp.Tool{ Name: "calculate", Description: "Perform arithmetic operations", } handler := func(ctx context.Context, req *mcp.CallToolRequest, args CalculateArgs) (*mcp.CallToolResult, any, error) { var result float64 switch args.Operation { case "add": result = args.A + args.B case "subtract": result = args.A - args.B case "multiply": result = args.A * args.B case "divide": if args.B == 0 { return &mcp.CallToolResult{IsError: true}, nil, fmt.Errorf("division by zero") } result = args.A / args.B } return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: fmt.Sprintf("Result: %v", result)}, }, }, result, nil } // Register tool mcp.AddTool(server, tool, handler) ``` -------------------------------- ### Manual Package Replacements Source: https://github.com/zeromicro/go-zero/blob/master/core/stores/mon/migration-2.0.md Examples of manual replacements for packages that are no longer present in v2 of the mongo-go-driver. ```go go.mongodb.org/mongo-driver/bson/bsonrw => go.mongodb.org/mongo-driver/v2/bson go.mongodb.org/mongo-driver/bson/bsoncodec => go.mongodb.org/mongo-driver/v2/bson go.mongodb.org/mongo-driver/bson/primitive => go.mongodb.org/mongo-driver/v2/bson ``` -------------------------------- ### Define Streaming RPCs Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Example of defining server, client, and bidirectional streaming in a proto file. ```protobuf service StreamService { rpc ServerStream(Req) returns (stream Reply); // Server streaming rpc ClientStream(stream Req) returns (Reply); // Client streaming rpc BidiStream(stream Req) returns (stream Reply); // Bidirectional streaming } ``` -------------------------------- ### Main function for Gateway Source: https://github.com/zeromicro/go-zero/blob/master/gateway/readme.md This Go code demonstrates the main function for starting a go-zero gateway server, including configuration loading. ```go var configFile = flag.String("f", "config.yaml", "config file") func main() { flag.Parse() var c gateway.GatewayConf conf.MustLoad(*configFile, &c) gw := gateway.MustNewServer(c) defer gw.Stop() gw.Start() } ``` -------------------------------- ### Correct Service Syntax Example (Recommended) Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Recommended way to write service definitions in goctl API. ```api @server( jwt: Auth group: foo middleware: AuthMiddleware ) service foo-api{ @doc "foo" @handler: foo post /foo/:id (Foo) returns (Bar) } service foo-api{ @handler ping get /ping @doc "foo" @handler: bar post /bar/:id (Foo) } ``` -------------------------------- ### Type-safe tool registration with Go generics Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md Example demonstrating type-safe tool registration using Go generics and automatic JSON schema generation. ```go import sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" type MyArgs struct { Value string `json:"value" jsonschema:"description=Input value" } tool := &mcp.Tool{ Name: "my_tool", Description: "Description", } handler := func(ctx context.Context, req *mcp.CallToolRequest, args MyArgs) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: "Result"}, }, }, nil, nil } // Register with explicit type parameters sdkmcp.AddTool(server.Server(), tool, handler) ``` -------------------------------- ### Correct Syntax Example (Recommended) Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Shows the recommended and standard way to define types, including exported fields and type blocks. ```api type Foo{ Id int `path:"id"` Foo int `json:"foo"` } type Bar{ Bar int `form:"bar"` } type( FooBar{ FooBar int } ) ``` -------------------------------- ### Doc and Comment Example for Various Syntax Blocks Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Demonstrates how to define documentation (doc) and comments for different syntax elements in goctl API definitions. ```api // syntaxLit doc syntax = "v1" // syntaxLit comment info( // kvLit doc author: songmeizi // kvLit comment ) // typeLit doc type Foo {} // typeLit comment type( // typeLit doc Bar{} // typeLit comment FooBar{ // filed doc Name int // filed comment } ) @server( /** * kvLit doc * 开启jwt鉴权 */ jwt: Auth /**kvLit comment*/ ) service foo-api{ // atHandler doc @handler foo //atHandler comment /* * route doc * post请求 * path为 /foo * 请求体:Foo * 响应体:Foo */ post /foo (Foo) returns (Foo) // route comment } ``` -------------------------------- ### Enable useDefinitions for Swagger Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/change.md Example of how to enable the `useDefinitions` keyword in an API file to generate definitions for Swagger. ```go syntax = "v1" info ( ... wrapCodeMsg: true useDefinitions: true ) ... ``` -------------------------------- ### Request Metadata Bridge Source: https://github.com/zeromicro/go-zero/blob/master/mcp/readme.md Example demonstrating how to extract request metadata (tenant ID, trace ID, scope) from the context in handlers. ```go server := mcp.NewMcpServerWithOptions(c, mcp.WithRequestMetadataExtractor(mcp.DefaultRequestMetadataExtractor), ) handler := func(ctx context.Context, req *mcp.CallToolRequest, args SomeArgs) (*mcp.CallToolResult, any, error) { tenant, _ := mcp.HeaderFromContext(ctx, "X-Tenant-Id") traceID, _ := mcp.QueryFromContext(ctx, "trace") scope, _ := mcp.PathFromContext(ctx, "scope") _ = tenant _ = traceID _ = scope return &mcp.CallToolResult{}, nil, nil } ``` -------------------------------- ### Incorrect Syntax Example (eg1) Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Demonstrates non-standard ways of defining types, including unexported fields and fields within a type block. ```api type Foo struct{ Id int `path:"id"` // ① Foo int `json:"foo"` } type Bar{ // 非导出型字段 bar int `form:"bar"` } type( // 非导出型结构体 fooBar struct{ FooBar int } ) ``` -------------------------------- ### Incorrect Syntax Examples Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Illustrates various incorrect syntax usages, including unsupported types like time.Time, aliasing, using Go keywords as identifiers, and invalid map key types. ```api type Gender int // 不支持 // 非struct token type Foo structure{ CreateTime time.Time // 不支持time.Time } // golang关键字 var type var{} type Foo{ // golang关键字 interface Foo interface } type Foo{ foo int // map key必须要golang内置数据类型 m map[Bar]string } ``` -------------------------------- ### Generate a proto template Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Create a starter proto file template for new services. ```bash goctl rpc template -o=<output_file> [flags] ``` -------------------------------- ### Generate proto template Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Creates a starter proto file template. ```bash goctl rpc template -o=user.proto ``` -------------------------------- ### Initialize New RPC Project Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/01-basic/README.md Use the goctl rpc new command to scaffold a complete RPC project structure. ```bash # Create a complete RPC project with one command goctl rpc new greeter ``` -------------------------------- ### Initialize Output Directory Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/01-basic/README.md Prepare the directory structure and Go module before generating code from an existing proto file. ```bash mkdir -p output && cd output && go mod init example.com/demo && cd .. ``` -------------------------------- ### Incorrect Java-style Doc Comment Example Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Examples of incorrectly formatted Java-style documentation comments. ```api /* * java-style doc */ */ ``` -------------------------------- ### Incorrect Service Syntax Example Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md Examples of incorrect syntax for service definitions in goctl API. ```api // 不支持空的server语法块 @server( ) // 不支持空的service语法块 service foo-api{ } service foo-api{ @doc kkkk // 简版doc必须用英文双引号引起来 @handler foo post /foo @handler foo // 重复的handler post /bar @handler fooBar post /bar // 重复的路由 // @handler和@doc顺序错误 @handler someHandler @doc "some doc" post /some/path // handler缺失 post /some/path/:id @handler reqTest post /foo/req (*Foo) // 不支持除普通结构体外的其他数据类型作为请求体 @handler replyTest post /foo/reply returns (*Foo) // 不支持除普通结构体、数组(向前兼容,后续考虑废弃)外的其他数据类型作为响应体 } ``` -------------------------------- ### Incorrect Single Line Comment Example Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md An example of an incorrectly formatted single-line comment that spans multiple lines. ```api // break line comments ``` -------------------------------- ### Incorrect Service Syntax Example (Non-standard) Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/api/parser/readme.md An example of a non-standard way to write service definitions in goctl API. ```api @server( jwt: Auth group: foo middleware: AuthMiddleware ) service foo-api{ @doc( summary: foo ) @server( handler: foo ) // 非导出型body post /foo/:id (foo) returns (bar) @doc "bar" @handler bar post /bar returns ([]int)// 不推荐数组作为响应体 @handler fooBar post /foo/bar (Foo) returns // 可以省略'returns' } ``` -------------------------------- ### Create a new RPC service Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Scaffold a complete RPC service project structure. ```bash goctl rpc new <service_name> [flags] ``` -------------------------------- ### Generate service code from proto Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Initializes the project and generates service code based on the provided proto file. ```bash mkdir -p output && cd output && go mod init example.com/demo && cd .. goctl rpc protoc user.proto \ --go_out=output --go-grpc_out=output --zrpc_out=output \ --go_opt=module=example.com/demo --go-grpc_opt=module=example.com/demo \ --module=example.com/demo -I . ``` -------------------------------- ### Tool registration comparison Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md Comparison of old and new methods for registering tools. ```go // Old (no longer supported) server.AddTool(tool, handler) // New (use SDK directly) sdkmcp.AddTool(server.Server(), tool, handler) ``` -------------------------------- ### Config Structure Definition Source: https://github.com/zeromicro/go-zero/blob/master/core/conf/readme.md Defines a Go struct for configuration, including fields with environment variable mapping, default values, options, optionality, and ranges. ```go type RestfulConf struct { ServiceName string `json:",env=SERVICE_NAME"` // read from env automatically ServiceName string `json:",env=SERVICE_NAME"` // read from env automatically Host string `json:",default=0.0.0.0" Port int LogMode string `json:",options=[file,console]" Verbose bool `json:",optional" MaxConns int `json:",default=10000" MaxBytes int64 `json:",default=1048576" Timeout time.Duration `json:",default=3s" CpuThreshold int64 `json:",default=900,range=[0:1000)" } ``` -------------------------------- ### Run the generated server Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Run the generated Go server and access it via curl. ```shell cd greet go run greet.go -f etc/greet-api.yaml ``` -------------------------------- ### Helper methods for primary key handling Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/model/sql/README.MD Helper methods for formatting primary keys and querying by primary key. ```go func (m *defaultUserModel) formatPrimary(primary any) string { return fmt.Sprintf("%s%v", cacheUserIdPrefix, primary) } func (m *defaultUserModel) queryPrimary(conn sqlx.SqlConn, v, primary any) error { query := fmt.Sprintf("select %s from %s where id = ? limit 1", userRows, m.table) return conn.QueryRow(v, query, primary) } ``` -------------------------------- ### API Parser with identifier values Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/change.md Example of using identifier values (true/false) for info key-value pairs in the API parser. ```go syntax = "v1" info( enable: true disable: false ) ... ``` -------------------------------- ### Create a new RPC service Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Generates a complete project structure for a new RPC service. ```bash goctl rpc new greeter ``` -------------------------------- ### Define group name using 'group' keyword Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/change.md Example of using the `group` keyword in an `@server` block to define a group name for services. ```go @server( group: user ) service demo{ ... } ``` -------------------------------- ### View goctl model mysql help Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/model/sql/README.MD Displays the help information for the goctl model mysql command. ```Plain Text goctl model mysql -h ``` ```Plain Text NAME: goctl model mysql - generate mysql model" USAGE: goctl model mysql command [command options] [arguments...] COMMANDS: ddl generate mysql model from ddl" datasource generate model from datasource" OPTIONS: --help, -h show help ``` -------------------------------- ### goctl api go command with type-group flag Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/change.md Example command for `goctl api go` with the `--type-group` flag to control output of types. ```bash goctl api go --api demo.api --dir demo --type-group ``` -------------------------------- ### Import Proto from Subdirectory Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/03-import-subdir/README.md Use the import statement to reference proto files located in subdirectories. ```protobuf import "common/types.proto"; ``` -------------------------------- ### Implement a custom Kafka writer for logx Source: https://github.com/zeromicro/go-zero/blob/master/core/logx/readme.md Create a custom writer by implementing the io.Writer interface and registering it with logx.SetWriter to redirect logs to a Kafka topic. ```go type KafkaWriter struct { Pusher *kq.Pusher } func NewKafkaWriter(pusher *kq.Pusher) *KafkaWriter { return &KafkaWriter{ Pusher: pusher, } } func (w *KafkaWriter) Write(p []byte) (n int, err error) { // writing log with newlines, trim them. if err := w.Pusher.Push(strings.TrimSpace(string(p))); err != nil { return 0, err } return len(p), nil } func main() { pusher := kq.NewPusher([]string{"localhost:9092"}, "go-zero") defer pusher.Close() writer := logx.NewWriter(NewKafkaWriter(pusher)) logx.SetWriter(writer) // more code } ``` -------------------------------- ### Run Tests Source: https://github.com/zeromicro/go-zero/blob/master/CONTRIBUTING.md Verify that your changes pass all the tests, including data race tests. ```shell go test -race ./... ``` -------------------------------- ### Specify External Proto Directories Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Use the -I or --proto_path flag to include additional directories for proto file resolution. ```bash # Search multiple directories for proto files goctl rpc protoc service.proto \ --go_out=output --go-grpc_out=output --zrpc_out=output \ --go_opt=module=example.com/demo --go-grpc_opt=module=example.com/demo \ --module=example.com/demo \ -I . -I ./shared_protos -I /path/to/external_protos ``` -------------------------------- ### Define Multiple Services in Proto Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md Use the --multiple flag when a single proto file contains multiple service definitions. ```protobuf service SearchService { rpc Search(SearchReq) returns (SearchReply); } service NotifyService { rpc Notify(NotifyReq) returns (NotifyReply); } ``` -------------------------------- ### Calculate sum of squares with MapReduce Source: https://github.com/zeromicro/go-zero/blob/master/core/mr/readme.md Demonstrates the use of MapReduce to generate numbers, map them to their squares, and reduce them into a single sum. ```go package main import ( "fmt" "log" "github.com/zeromicro/go-zero/core/mr" ) func main() { val, err := mr.MapReduce(func(source chan<- int) { // generator for i := 0; i < 10; i++ { source <- i } }, func(i int, writer mr.Writer[int], cancel func(error)) { // mapper writer.Write(i * i) }, func(pipe <-chan int, writer mr.Writer[int], cancel func(error)) { // reducer var sum int for i := range pipe { sum += i } writer.Write(sum) }) if err != nil { log.Fatal(err) } fmt.Println("result:", val) } ``` -------------------------------- ### Define Proto Package Options Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/03-import-subdir/README.md Specify the go_package option for individual proto files to ensure they compile into separate Go packages. ```protobuf option go_package = "example.com/demo/pb"; ``` ```protobuf option go_package = "example.com/demo/pb/common"; ``` -------------------------------- ### Define Proto Package Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/01-basic/README.md Specify the Go package path in the proto file using a full module path. ```protobuf option go_package = "example.com/demo/greeter"; ``` -------------------------------- ### Generate Multiple Services Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/05-multiple-services/README.md Use the -m flag with goctl rpc protoc to generate code for multiple services defined in one proto file. ```bash goctl rpc protoc multi.proto \ --go_out=output \ --go-grpc_out=output \ --zrpc_out=output \ --go_opt=module=example.com/demo \ --go-grpc_opt=module=example.com/demo \ --module=example.com/demo \ -I . \ -m ``` -------------------------------- ### Default Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md The default directory structure when --multiple=false is used. ```text output/ ├── greeterclient/ │ └── greeter.go ├── internal/ │ ├── logic/ │ │ └── sayhellologic.go │ └── server/ │ └── greeterserver.go └── ... ``` -------------------------------- ### View Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/06-wellknown-types/README.md Displays the file structure created by the goctl generation command. ```text output/ ├── etc │ └── eventsvc.yaml ├── eventservice │ └── eventservice.go ├── eventsvc.go ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ ├── createeventlogic.go │ │ └── listeventslogic.go │ ├── server │ │ └── eventserviceserver.go │ └── svc │ └── servicecontext.go └── pb ├── events.pb.go └── events_grpc.pb.go ``` -------------------------------- ### Project Directory Layout Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/07-external-proto-same-pkg/README.md The structure showing the external proto file in a separate directory. ```text 07-external-proto-same-pkg/ ├── ext_protos │ └── ext.proto # External proto (go_package = "example.com/demo/pb") ├── service.proto # Service definition (go_package = "example.com/demo/pb") ├── README.md ├── README-cn.md └── README-ko.md ``` -------------------------------- ### Project Directory Layout Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/08-external-proto-diff-pkg/README.md The structure of the project showing the separation of service and external proto files. ```text 08-external-proto-diff-pkg/ ├── ext_protos │ └── common │ └── types.proto # External proto (go_package = "example.com/demo/pb/common") ├── service.proto # Service definition (go_package = "example.com/demo/pb") ├── README.md ├── README-cn.md └── README-ko.md ``` -------------------------------- ### Generate RPC Code from Proto Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/01-basic/README.md Execute the goctl rpc protoc command to generate service code from a defined proto file. ```bash goctl rpc protoc greeter.proto \ --go_out=output \ --go-grpc_out=output \ --zrpc_out=output \ --go_opt=module=example.com/demo \ --go-grpc_opt=module=example.com/demo \ --module=example.com/demo \ -I . ``` -------------------------------- ### Project structure output Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md The directory structure generated by the goctl rpc new command. ```text greeter/ ├── etc/ │ └── greeter.yaml ├── greeter/ │ ├── greeter.pb.go │ └── greeter_grpc.pb.go ├── greeter.go ├── greeter.proto ├── greeterclient/ │ └── greeter.go └── internal/ ├── config/ │ └── config.go ├── logic/ │ └── pinglogic.go ├── server/ │ └── greeterserver.go └── svc/ └── servicecontext.go ``` -------------------------------- ### Import Sibling Proto File Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/02-import-sibling/README.md Use the import statement to reference a proto file located in the same directory. ```protobuf import "types.proto"; ``` -------------------------------- ### View Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/04-transitive-import/README.md The resulting file structure after running the generation command. ```text output/ ├── etc │ └── pingsvc.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ └── pinglogic.go │ ├── server │ │ └── pingserviceserver.go │ └── svc │ └── servicecontext.go ├── pb │ ├── base.pb.go │ ├── main.pb.go │ ├── main_grpc.pb.go │ └── middleware.pb.go ├── pingservice │ └── pingservice.go └── pingsvc.go ``` -------------------------------- ### View Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/09-google-types-as-rpc/README.md The resulting file structure after running the generation command. ```text output/ ├── etc │ └── healthsvc.yaml ├── go.mod ├── healthservice │ └── healthservice.go ├── healthsvc.go ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ ├── gettimelogic.go │ │ └── pinglogic.go │ ├── server │ │ └── healthserviceserver.go │ └── svc │ └── servicecontext.go └── pb ├── service.pb.go └── service_grpc.pb.go ``` -------------------------------- ### Generate .api template Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Command to generate a template for an API file. ```shell goctl api -o greet.api ``` -------------------------------- ### Generated project structure Source: https://github.com/zeromicro/go-zero/blob/master/readme.md The directory structure created after running the goctl api go command. ```text ├── greet │ ├── etc │ │ └── greet-api.yaml // configuration file │ ├── greet.go // main file │ └── internal │ ├── config │ │ └── config.go // configuration definition │ ├── handler │ │ ├── greethandler.go // get/put/post/delete routes are defined here │ │ └── routes.go // routes list │ ├── logic │ │ └── greetlogic.go // request logic can be written here │ ├── svc │ │ └── servicecontext.go // service context, mysql/redis can be passed in here │ └── types │ └── types.go // request/response defined here └── greet.api // api description file ``` -------------------------------- ### Generate RPC Code Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/07-external-proto-same-pkg/README.md Run the goctl command with the -I flag to include the external directory in the search path. ```bash goctl rpc protoc service.proto \ --go_out=output \ --go-grpc_out=output \ --zrpc_out=output \ --go_opt=module=example.com/demo \ --go-grpc_opt=module=example.com/demo \ --module=example.com/demo \ -I . -I ./ext_protos ``` -------------------------------- ### View generated directory structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/10-streaming/README.md Overview of the file layout produced by the goctl generation command. ```text output/ ├── etc │ └── streamsvc.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ ├── bidistreamlogic.go │ │ ├── clientstreamlogic.go │ │ └── serverstreamlogic.go │ ├── server │ │ └── streamserviceserver.go │ └── svc │ └── servicecontext.go ├── pb │ ├── stream.pb.go │ └── stream_grpc.pb.go ├── streamservice │ └── streamservice.go └── streamsvc.go ``` -------------------------------- ### View Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/05-multiple-services/README.md The resulting directory structure organizes client, logic, and server code into subdirectories based on service names. ```text output/ ├── client │ ├── notifyservice │ │ └── notifyservice.go │ └── searchservice │ └── searchservice.go ├── etc │ └── multisvc.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ ├── notifyservice │ │ │ └── notifylogic.go │ │ └── searchservice │ │ └── searchlogic.go │ ├── server │ │ ├── notifyservice │ │ │ └── notifyserviceserver.go │ │ └── searchservice │ │ └── searchserviceserver.go │ └── svc │ └── servicecontext.go ├── multisvc.go └── pb ├── multi.pb.go ├── multi_grpc.pb.go └── shared.pb.go ``` -------------------------------- ### Generate RPC Code Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/02-import-sibling/README.md Execute the goctl rpc command to generate code from the proto file containing service definitions. ```bash goctl rpc protoc user.proto \ --go_out=output \ --go-grpc_out=output \ --zrpc_out=output \ --go_opt=module=example.com/demo \ --go-grpc_opt=module=example.com/demo \ --module=example.com/demo \ -I . ``` -------------------------------- ### Upgrade Go Modules Source: https://github.com/zeromicro/go-zero/blob/master/core/stores/mon/migration-2.0.md Command to upgrade the go.mongodb.org/mongo-driver module to the latest version. ```bash mod upgrade --mod-name=go.mongodb.org/mongo-driver ``` -------------------------------- ### View Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/02-import-sibling/README.md The resulting directory structure after running the generation command. ```text output/ ├── etc │ └── usersvc.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ ├── createuserlogic.go │ │ └── getuserlogic.go │ ├── server │ │ └── userserviceserver.go │ └── svc │ └── servicecontext.go ├── pb │ ├── types.pb.go │ ├── user.pb.go │ └── user_grpc.pb.go ├── userservice │ └── userservice.go └── usersvc.go ``` -------------------------------- ### Multiple Services Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/README.md The directory structure generated when --multiple=true is used. ```text output/ ├── client/ │ ├── searchservice/ │ │ └── searchservice.go │ └── notifyservice/ │ └── notifyservice.go ├── internal/ │ ├── logic/ │ │ ├── searchservice/ │ │ │ └── searchlogic.go │ │ └── notifyservice/ │ │ └── notifylogic.go │ └── server/ │ ├── searchservice/ │ │ └── searchserviceserver.go │ └── notifyservice/ │ └── notifyserviceserver.go └── ... ``` -------------------------------- ### Simplified McpServer interface Source: https://github.com/zeromicro/go-zero/blob/master/mcp/MIGRATION.md The new McpServer interface in the official SDK. ```go type McpServer interface { Start() Stop() Server() *sdkmcp.Server // Returns underlying SDK server } ``` -------------------------------- ### Generate Go server code Source: https://github.com/zeromicro/go-zero/blob/master/readme.md Command to generate Go server code from an API definition file. ```shell goctl api go -api greet.api -dir greet ``` -------------------------------- ### Generated Directory Structure Source: https://github.com/zeromicro/go-zero/blob/master/tools/goctl/rpc/example/07-external-proto-same-pkg/README.md The resulting file structure after running the generation command. ```text output/ ├── etc │ └── svc.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── logic │ │ └── querylogic.go │ ├── server │ │ └── queryserviceserver.go │ └── svc │ └── servicecontext.go ├── pb │ ├── ext.pb.go │ ├── service.pb.go │ └── service_grpc.pb.go ├── queryservice │ └── queryservice.go └── svc.go ``` -------------------------------- ### Generate frontend code Source: https://github.com/zeromicro/go-zero/wiki/go‐zero Generate frontend code for different languages from the API definition. ```shell goctl api java -api greet.api -dir greet goctl api dart -api greet.api -dir greet ... ```