### Cloning the tRPC-Go Example Repository (Bash) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Clones the tRPC-Go repository with a depth of 1 to get the latest version quickly and then changes the current directory to the helloworld example project. ```bash $ git clone --depth 1 git@github.com:trpc-group/trpc-go.git $ cd trpc-go/examples/helloworld ``` -------------------------------- ### Running the tRPC-Go Client Example (Bash) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Navigates into the 'client' subdirectory of the helloworld example and executes the main Go client application to interact with the running server. ```bash $ cd client && go run main.go ``` -------------------------------- ### Running the tRPC-Go Server Example (Bash) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Navigates into the 'server' subdirectory of the helloworld example and executes the main Go server application. ```bash $ cd server && go run main.go ``` -------------------------------- ### Start trpc-go Server (Cancellation Example) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/cancellation/README.md Command to start the trpc-go server for the cancellation example, specifying the configuration file. ```Shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Run Feature Example Client (shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/README.md Command to start the client implementation of a feature example, specifying the configuration file located in the client directory. ```shell go run client/main.go -conf client/trpc_go.yaml ``` -------------------------------- ### Start tRPC-Go HTTP Server (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/http/README.md Command to compile and run the tRPC-Go server example using the specified configuration file `server/trpc_go.yaml`. ```shell go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Run Feature Example Server (shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/README.md Command to start the server implementation of a feature example, specifying the configuration file located in the server directory. ```shell go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### trpc-go Server Initialization (main.go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.zh_CN.md Presents the main function responsible for initializing and starting the trpc server. It demonstrates importing necessary packages, creating a new server instance, registering the generated Flatbuffers services (handling multiple services), and starting the server. ```go package main import ( "flag" _ "trpc.group/trpc-go/trpc-filter/debuglog" _ "trpc.group/trpc-go/trpc-filter/recovery" trpc "trpc.group/trpc-go/trpc-go" "trpc.group/trpc-go/trpc-go/log" fb "github.com/trpcprotocol/testapp/greeter" ) func main() { flag.Parse() s := trpc.NewServer() // 如果是多 service 的话需要在第一个参数明确写上 service 名,否则流式会有问题 fb.RegisterGreeterService(s.Service("trpc.testapp.greeter.Greeter"), &greeterServiceImpl{}) fb.RegisterGreeter2Service(s.Service("trpc.testapp.greeter.Greeter2"), &greeter2ServiceImpl{}) if err := s.Serve(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Running trpc-go Client Example Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/metadata/README.md Command to start the trpc-go client example application with a specified configuration file. ```shell go run client/client.go -conf client/trpc_go.yaml ``` -------------------------------- ### Run tRPC-Go Client Bash Source: https://github.com/trpc-group/trpc-go/blob/main/examples/helloworld/README.md Navigates to the client directory and executes the main Go file to start the tRPC-Go client. This command is run in a separate terminal after the server is started. ```bash cd client && go run main.go ``` -------------------------------- ### Starting trpc-go Server (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/selector/README.md Command to start the trpc-go server using the specified configuration file. ```shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Running trpc-go Server Example Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/metadata/README.md Command to start the trpc-go server example application with a specified configuration file. ```shell go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Starting tRPC Server with Configuration (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/discovery/README.md This command starts the tRPC server application. It executes the `main.go` file located in the `server` directory and specifies the server configuration file `server/trpc_go.yaml` using the `-conf` flag. This is necessary to launch the server with the correct settings, including service discovery configuration. ```shell go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Building and Running the trpc-go Server Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.zh_CN.md Provides the shell commands to compile the generated Go server code and execute the resulting binary to start the trpc server. ```sh $ go build # 编译 $ ./testgreeter # 运行 ``` -------------------------------- ### Implementing the HelloAgain Server Method (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Provides the Go implementation for the new 'HelloAgain' RPC method on the server side, demonstrating how to handle the request context and message, log the request, and construct the response. ```go func (g Greeter) HelloAgain(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { log.Infof("got HelloAgain request: %s", req.Msg) return &pb.HelloReply{Msg: "Hello " + req.Msg + " again!"}, nil } ``` -------------------------------- ### Run tRPC-Go Server Bash Source: https://github.com/trpc-group/trpc-go/blob/main/examples/helloworld/README.md Navigates to the server directory and executes the main Go file to start the tRPC-Go server. This command is run in a terminal. ```bash cd server && go run main.go ``` -------------------------------- ### Starting tRPC-Go Server with Config (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/log/README.md Command to start the tRPC-Go server application, specifying a configuration file using the '-conf' flag. ```Shell go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Starting tRPC Client (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/discovery/README.md This command starts the tRPC client application. It executes the `main.go` file located in the `client` directory. The client will then attempt to connect to the server using the configured service discovery mechanism. ```shell go run client/main.go ``` -------------------------------- ### Initial Greeter Service Definition (Protobuf) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Defines the initial Protobuf service 'Greeter' with a single RPC method 'Hello' that takes a 'HelloRequest' and returns a 'HelloReply', along with the message structures. ```protobuf service Greeter { rpc Hello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string msg = 1; } message HelloReply { string msg = 1; } ``` -------------------------------- ### Starting tRPC-go Server Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/errs/README.md Command to start the tRPC-go server using the Go run command and specifying a configuration file. ```Shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Start RPCZ Server with Basic Configuration (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/rpcz/README.md Command to start the RPCZ server configured for basic sampling of all spans. Requires the server binary and the basic configuration file. ```shell go run server/main.go -conf server/trpc_go.yaml -type Basic ``` -------------------------------- ### Start trpc-go Client (Cancellation Example) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/cancellation/README.md Command to start the trpc-go client that interacts with the server to demonstrate cancellation. ```Shell $ go run client/main.go ``` -------------------------------- ### Start trpc-go Server (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/loadbalance/README.md Command to start the trpc-go server using the specified configuration file. This command executes the main server program. ```shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Starting tRPC-Go Client (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/log/README.md Command to start the tRPC-Go client application, which will interact with the running server and generate client-side logs. ```Shell go run client/main.go ``` -------------------------------- ### Start trpc-go Client Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/config/README.md Starts the trpc-go client application. The client will interact with the running server to demonstrate how configuration values loaded by the server can be accessed or reflected in the server's response. ```shell $ go run client/main.go ``` -------------------------------- ### Calling the HelloAgain Client Method (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Shows how to call the newly added 'HelloAgain' RPC method from the client side using the generated stub, including passing the context and request message, handling potential errors, and logging the successful response. ```go rsp, err = c.HelloAgain(context.Background(), &pb.HelloRequest{Msg: "world"}) if err != nil { log.Error(err) } log.Info(rsp.Msg) ``` -------------------------------- ### Starting trpc-go Client (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/selector/README.md Command to start the trpc-go client using the specified configuration file. The target can also be set programmatically. ```shell $ go run client/main.go -conf client/trpc_go.yaml ``` -------------------------------- ### Start RPCZ Server with Code Configuration (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/rpcz/README.md Command to start the RPCZ server configured for code-based dynamic sampling. Requires the server binary and the basic configuration file, with sampling logic defined in code. ```shell go run server/main.go -conf server/trpc_go.yaml -type Code ``` -------------------------------- ### Internal Service Call Example (Mode 1) - Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/client/overview.md Demonstrates how a trpc-go service implementation (greeterServerImpl) makes a client call to a downstream service (SayHi) within its request handler (SayHello). It shows creating a client proxy and passing the context (ctx). The main function illustrates initializing and starting the trpc server in Mode 1, which automatically handles plugin initialization via configuration. ```Go import ( "trpc.group/trpc-go/trpc-go/errs" // The Git address for the generated protocol file pb.go of the called service and the protocol interface management can be found here: todo pb "github.com/trpcprotocol/app/server" ) // SayHello is the entry function for server requests. Generally, client calls are made within a service to call downstream services // SayHello carries ctx information, and when calling downstream services within this function, ctx needs to be passed through all the way func (s *greeterServerImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { // Create a client call proxy. This operation is lightweight and does not create a connection. It can be created for each request or a global proxy can be initialized. It is recommended to put it in the service impl struct for easy mock testing. For detailed demos, please refer to the framework source code examples/helloworld. proxy := pb.NewGreeterClientProxy() // In normal cases, do not specify any option parameters in the code. Use configuration for greater flexibility. If you specify options, the options have the highest priority reply, err := proxy.SayHi(ctx, req) if err != nil { log.ErrorContextf(ctx, "say hi fail:%v", err) return nil, errs.New(10000, "xxxxx") } return &pb.HelloReply{Xxx: reply.Xxx} nil } func main(){ // Create a service object, which will automatically read the service configuration and initialize the plugins. It must be placed at the beginning of the main function. The business initialization logic must be placed after NewServer s := trpc.NewServer() // Register the current implementation to the service object pb.RegisterService(s, &greeterServerImpl{}) // Start the service and block here if err := s.Serve(); err != nil { panic(err) } } ``` -------------------------------- ### Starting trpc-go Server (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/compression/README.md Command to start the trpc-go server using a specific configuration file. This is the initial step required before running the client. ```shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Start RPCZ Client (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/rpcz/README.md Command to start the RPCZ client. This client will generate RPC traffic that the RPCZ server can monitor. Requires the client binary and its configuration file. ```shell go run client/main.go -conf client/trpc_go.yaml ``` -------------------------------- ### Start trpc-go Client (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/loadbalance/README.md Command to start the trpc-go client. This command executes the main client program which interacts with the running server. ```shell $ go run client/main.go ``` -------------------------------- ### Start trpc-go Server with Custom Config Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/config/README.md Starts the trpc-go server application, specifying the path to the custom configuration file using the `-conf` flag. This allows the server to load and use the defined configuration settings. ```shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Starting tRPC-go Client Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/errs/README.md Command to start the tRPC-go client using the Go run command to interact with the running server. ```Shell $ go run client/main.go ``` -------------------------------- ### Example Output: Viewing Framework Version (JSON) Source: https://github.com/trpc-group/trpc-go/blob/main/admin/README.md This JSON snippet provides an example of the response received from the `/version` admin endpoint, containing the framework version string. ```json { "errorcode": 0, "message": "", "version": "v0.1.0-dev" } ``` -------------------------------- ### Start RPCZ Server with Advanced Configuration (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/rpcz/README.md Command to start the RPCZ server configured for advanced sampling, allowing selection of spans based on specific criteria. Requires the server binary and the advanced configuration file. ```shell go run server/main.go -conf server/trpc_go_rpcz_error.yaml -type Advanced ``` -------------------------------- ### Example Output: Viewing Configuration (JSON) Source: https://github.com/trpc-group/trpc-go/blob/main/admin/README.md This JSON snippet shows an example response from the `/cmds/config` endpoint, containing the service's configuration content within the 'content' field. ```json { "content":{ }, "errorcode":0, "message":"" } ``` -------------------------------- ### Updated Greeter Service Definition (Protobuf) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/quick_start.md Modifies the Protobuf service 'Greeter' by adding a new RPC method 'HelloAgain' which also uses the 'HelloRequest' and 'HelloReply' message types. ```protobuf service Greeter { rpc Hello (HelloRequest) returns (HelloReply) {} rpc HelloAgain (HelloRequest) returns (HelloReply) {} } message HelloRequest { string msg = 1; } message HelloReply { string msg = 1; } ``` -------------------------------- ### trpc Server Initialization and Service Registration (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.md Shows the Go code for the server's main function. It initializes a new trpc server, registers the Greeter and Greeter2 services with specific service names, and starts the server to listen for incoming requests. ```go package main import ( "flag" _ "trpc.group/trpc-go/trpc-filter/debuglog" _ "trpc.group/trpc-go/trpc-filter/recovery" trpc "trpc.group/trpc-go/trpc-go" "trpc.group/trpc-go/trpc-go/log" fb "github.com/trpcprotocol/testapp/greeter" ) func main() { flag.Parse() s := trpc.NewServer() // If there are multiple services, the service name must be explicitly written as the first parameter, otherwise the stream will have issues. fb.RegisterGreeterService(s.Service("trpc.testapp.greeter.Greeter"), &greeterServiceImpl{}) fb.RegisterGreeter2Service(s.Service("trpc.testapp.greeter.Greeter2"), &greeter2ServiceImpl{}) if err := s.Serve(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Example Output: Setting Log Level (JSON) Source: https://github.com/trpc-group/trpc-go/blob/main/admin/README.md This JSON snippet is an example response after successfully setting the log level, showing the new ('level') and previous ('prelevel') log levels. ```json { "errorcode":0, "level":"debug", "message":"", "prelevel":"info" } ``` -------------------------------- ### Show Feature Example Directory Structure (shell) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/README.md Displays the required directory structure for a new feature example, including README, client, server, and optional shared folders, along with specific file names like main.go and trpc_go.yaml. ```shell tree somefeature/ somefeature/ ├── README.md ├── client/ │ ├── main.go | └── trpc_go.yaml │── server/ │ ├── main.go | └── trpc_go.yaml └── shared/ # optional └── utility.go ``` -------------------------------- ### Pure Client Tool Example (Mode 2) - Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/client/overview.md Shows how to create a simple trpc-go client tool without a configuration file (Mode 2). It requires manually registering necessary plugins (like a naming service) and using trpc.BackgroundContext() as there's no request context. Client options, such as the target address, must be specified directly in the code using client.WithTarget. ```Go import ( "trpc.group/trpc-go/trpc-go/client" pb "github.com/trpcprotocol/app/server" pselector "trpc.group/trpc-go/trpc-naming-polarismesh/selector" // You need to import the required naming service plugin code yourself trpc "trpc.group/trpc-go/trpc-go" ) // Generally, small tools start from the main function func main { // Since there is no configuration file to help initialize the plugin, you need to manually initialize the North Star pselector.RegisterDefault() // Create a client call proxy proxy := pb.NewGreeterClientProxy() // You must create ctx yourself through trpc.BackgroundContext() and pass in option parameters through code. rsp, err := proxy.SayHi(trpc.BackgroundContext(), req, client.WithTarget("ip://ip:port")) if err != nil { log.Errorf("say hi fail:%v", err) return } return } ``` -------------------------------- ### Constructing Flatbuffers Message Step-by-Step (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.md Provides a detailed breakdown of the steps required to construct a Flatbuffers message (`fb.HelloRequest`) using the `flatbuffers.Builder` in Go. It covers importing the stub package, initializing the builder, creating primitive types (like strings), starting and ending struct construction, and adding fields. Requires `flatbuffers` and generated Flatbuffers code. ```Go // Import the package containing the stub code. import fb "github.com/trpcprotocol/testapp/greeter" // Start by creating a *flatbuffers.Builder. b := flatbuffers.NewBuilder(0) // To populate a field in a struct: // First create an object of the type that the field represents. // For example, if the field is of type String, // you can call b.CreateString("a string") to create the string. // This method returns the index of the string in the flatbuffer. i := b.CreateString("GreeterSayHello") // To construct a HelloRequest struct: // Call the XXXXStart method provided in the stub code to indicate the start of constructing this struct. // The corresponding end method is fb.HelloRequestEnd. fb.HelloRequestStart(b) // If the field to be populated is called message, you can call fb.HelloRequestAddMessage(b, i) to construct the message field by passing the builder and the index of the previously constructed string. // Other fields can be constructed in a similar manner. fb.HelloRequestAddMessage(b, i) // Call the XXXEnd method when the struct is complete. // This method will return the index of the struct in the flatbuffer. // Then call b.Finish to complete the construction of the flatbuffer. b.Finish(fb.HelloRequestEnd(b)) ``` -------------------------------- ### Example Output: Listing Admin Commands (JSON) Source: https://github.com/trpc-group/trpc-go/blob/main/admin/README.md This JSON snippet shows an example response from the `/cmds` endpoint, listing the available command paths under the 'cmds' array. 'errorcode' 0 indicates success. ```json { "cmds":[ "/cmds", "/version", "/cmds/loglevel", "/cmds/config" ], "errorcode":0, "message":"" } ``` -------------------------------- ### Example IDL Service Call (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/client/overview.zh_CN.md Demonstrates a complete example of calling an IDL-based service. It shows how to create a ClientProxy, prepare the request parameters, make the synchronous call, and process the response. ```go import ( "context" "trpc.group/trpc-go/trpc-go/client" "trpc.group/trpc-go/trpc-go/log" pb "github.com/trpcprotocol/test/helloworld" ) func main() { // 创建 ClientProxy proxy := pb.NewGreeterClientProxy() // 填充请求参数 req := &pb.HelloRequest{Msg: "Hello, I am tRPC-Go client."} // 调用服务请求接口 rsp, err := proxy.SayHello(context.Background(), req, client.WithTarget("ip://127.0.0.1:8000")) if err != nil { return } // 获取请求响应数据 log.Debugf("response: %v", rsp) } ``` -------------------------------- ### Example trpc-go Client Output (Text) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/selector/README.md Example log output from the trpc-go client showing a successful response. ```text 2023-05-25 16:39:45.767 INFO client/main.go:40 SayHello success rsp[msg:"Hello Hi trpc-go-client"] ``` -------------------------------- ### Implementing Flatbuffers Unary Service Method (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.zh_CN.md Provides an example implementation for a unary RPC method (`SayHello`) of a Flatbuffers service. It shows how to access fields from the Flatbuffers request object and how to construct and return a Flatbuffers response using a `flatbuffers.Builder`. ```go func (s *greeterServiceImpl) SayHello(ctx context.Context, req *fb.HelloRequest) (*flatbuffers.Builder, error) { // 单发单收 flatbuffers 处理逻辑(仅供参考,请根据需要修改) log.Debugf("Simple server receive %v", req) // 将 Message 替换为你想要操作的字段名 v := req.Message() // Get Message field of request. var m string if v == nil { m = "Unknown" } else { m = string(v) } // 添加字段示例 // 将 CreateString 中的 String 替换为你想要操作的字段类型 // 将 AddMessage 中的 Message 替换为你想要操作的字段名 idx := b.CreateString("welcome " + m) // 创建一个 flatbuffers 中的字符串 b := &flatbuffers.Builder{} fb.HelloReplyStart(b) fb.HelloReplyAddMessage(b, idx) b.Finish(fb.HelloReplyEnd(b)) return b, nil } ``` -------------------------------- ### Implementing tRPC-Go Integration Test Suite (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/test/README.md Provides the core Go code for the tRPC-Go integration test suite, demonstrating how suite.Run is used to execute test methods (TestAdmin) within a TestSuite, including setup (SetupSuite, SetupTest) and teardown (TearDownTest, TearDownSuite) methods, and how individual test cases (testCmds, etc.) are run using s.Run. It also shows an example test case (testCmds) making an HTTP request and asserting the response. ```go func TestRunSuite(t *testing.T) { suite.Run(t, new(TestSuite)) } func (s *TestSuite) SetupSuite() {} func (s *TestSuite) SetupTest() {} func (s *TestSuite) TestAdmin() { s.copyTRPCConfigFile(defaultTRPCWithAdminConfigPath) s.startTRPCServerWithListener(&TRPCService{}) // wait a while until admin server has started. time.Sleep(200 * time.Millisecond) s.Run("cmds", s.testCmds) s.Run("cmds-config", s.testCmdsConfig) s.Run("cmds-loglevel", s.testCmdsLogLevel) s.Run("CustomHandleFunc", s.testCustomHandleFunc) s.Run("is-healthy", s.testIsHealthy) } func (s *TestSuite) testCmds(){ resp, err := httpRequest(http.MethodGet, fmt.Sprintf("http://%s/cmds", defaultAdminListenAddr), "") require.Nil(s.T(), err) r := struct { Errcode int `json:"errorcode"` Message string `json:"message"` Cmds []string `json:"cmds"` }{} require.Nil(s.T(), json.Unmarshal(resp, &r), "Unmarshal failed") require.ElementsMatch( s.T(), []string{ "/cmds", "/version", "/debug/pprof/", "/debug/pprof/symbol", "/debug/pprof/trace", "/cmds/loglevel", "/cmds/config", "/is_healthy/", "/debug/pprof/cmdline", "/debug/pprof/profile" }, r.Cmds, ) } func (s *TestSuite) TearDownTest() {} func (s *TestSuite) TearDownSuite() {} ``` -------------------------------- ### Starting trpc-go Server Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/stream/README.md Command to start the trpc-go server using the specified configuration file. ```shell $ go run server/main.go -conf server/trpc_go.yaml ``` -------------------------------- ### Example Output: Viewing Log Level (JSON) Source: https://github.com/trpc-group/trpc-go/blob/main/admin/README.md This JSON snippet shows an example response when querying the log level via `/cmds/loglevel`, indicating the current log level for the specified logger/output. ```json { "errorcode":0, "loglevel":"info", "message":"" } ``` -------------------------------- ### Calling IDL Service using tRPC-Go ClientProxy Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/client/overview.md This Go example demonstrates how to make a synchronous call to an IDL-based tRPC service. It shows creating the ClientProxy using the generated function, preparing the request struct, invoking the service method with context and options, and handling the response or error. It requires importing necessary tRPC-Go packages and the generated protobuf code. ```go import ( "context" "trpc.group/trpc-go/trpc-go/client" "trpc.group/trpc-go/trpc-go/log" pb "github.com/trpcprotocol/test/helloworld" ) func main() { // Create ClientProxy. proxy := pb.NewGreeterClientProxy() // Fill in the request parameters. req := &pb.HelloRequest{Msg: "Hello, I am tRPC-Go client."} // Call the service request interface. rsp, err := proxy.SayHello(context.Background(), req, client.WithTarget("ip://127.0.0.1:8000")) if err != nil { return } // Get the request response data. log.Debugf("response: %v", rsp) } ``` -------------------------------- ### Defining a Protobuf Service with RPC Method Source: https://github.com/trpc-group/trpc-go/blob/main/docs/basics_tutorial.zh_CN.md Shows how to define a service (`Greeter`) with an RPC method (`Hello`) that takes a request message (`HelloReq`) and returns a response message (`HelloRsp`), along with the message definitions. ```protobuf service Greeter { rpc Hello(HelloReq) returns (HelloRsp) {} // ... } message HelloReq { // ... } message HelloRsp { // ... } ``` -------------------------------- ### tRPC-Go Client YAML Configuration Example Source: https://github.com/trpc-group/trpc-go/blob/main/client/README.zh_CN.md This YAML snippet provides an example of how to configure the tRPC-Go client using a configuration file. It includes global settings for timeout, namespace, and filters, as well as service-specific configurations for target, network, protocol, timeout, serialization, and compression, illustrating how to define settings for different called services. ```yaml client: # 客户端配置 timeout: 1000 # 所有请求最长处理时间(ms) namespace: Development # 所有请求服务端的环境 filter: # 所有请求的拦截器 - debuglog # 使用 debuglog 打印具体请求和响应数据 service: # 请求特定服务端的配置 - callee: trpc.test.helloworld.Greeter # 请求服务端协议文件的 service name, 如果 callee 和下面的 name 一样,那只需要配置其中之一即可 name: trpc.test.helloworld.Greeter1 # 请求服务名字路由的 service name target: ip://127.0.0.1:8000 # 服务端地址,如果 name 可以直接用作服务发现,则可以不用配置,例如 ip://ip:port, polaris://servicename network: tcp # 请求的网络类型 tcp udp protocol: trpc # 应用层协议 trpc http timeout: 800 # 请求超时时间(ms) serialization: 0 # 序列化方式 0-pb 2-json 3-flatbuffer,默认不用配置 compression: 1 # 压缩方式 1-gzip 2-snappy 3-zlib,默认不用配置 ``` -------------------------------- ### Defining trpc Services with Flatbuffers IDL Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.md Defines two RPC services, Greeter and Greeter2, using Flatbuffers IDL syntax. It includes examples of single-send/receive, client streaming, server streaming, and bidirectional streaming methods. It also shows how to specify the Go package attribute. ```idl namespace trpc.testapp.greeter; // Equivalent to the "package" in protobuf. // Equivalent to the "go_package" statement in protobuf. // Note: "attribute" is a standard syntax in flatbuffers, and the "go_package=xxx" syntax is a custom support implemented by trpc-cmdline. attribute "go_package=github.com/trpcprotocol/testapp/greeter"; table HelloReply { // "table" is equivalent to "message" in protobuf. Message:string; } table HelloRequest { Message:string; } rpc_service Greeter { SayHello(HelloRequest):HelloReply; // Single-send and single-receive. SayHelloStreamClient(HelloRequest):HelloReply (streaming: "client"); // Client streaming. SayHelloStreamServer(HelloRequest):HelloReply (streaming: "server"); // Server streaming. SayHelloStreamBidi(HelloRequest):HelloReply (streaming: "bidi"); // Bidirectional streaming. } // Example with two services. rpc_service Greeter2 { SayHello(HelloRequest):HelloReply; SayHelloStreamClient(HelloRequest):HelloReply (streaming: "client"); SayHelloStreamServer(HelloRequest):HelloReply (streaming: "server"); SayHelloStreamBidi(HelloRequest):HelloReply (streaming: "bidi"); } ``` -------------------------------- ### Starting TRPC Server with Registered Service in Go Source: https://github.com/trpc-group/trpc-go/blob/main/restful/README.md Initializes a new tRPC server instance, registers the Greeter service implementation generated from the Protocol Buffers definition, and starts the server to listen for incoming requests (either tRPC or RESTful based on configuration). ```go package main import ( ... pb "trpc.group/trpc-go/trpc-go/examples/restful/helloworld" ) func main() { s := trpc.NewServer() pb.RegisterGreeterService(s, &greeterServerImpl{}) // Start if err := s.Serve(); err != nil { ... } } ``` -------------------------------- ### Implementing and Registering tRPC Hello Service (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/server/README.md Shows how to implement the `hello` service logic in Go and register it with different logical services (`HelloTrpc`, `HelloHttp`) within a tRPC server instance, demonstrating both separate and combined registration methods. ```Go type helloImpl struct{} func (s *helloImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { rsp := &pb.HelloReply{} // implement business logic here ... return rsp, nil } func main() { s := trpc.NewServer() // Recommended: Register a proto service for each service separately pb.RegisterHiServer(s.Service("trpc.test.helloworld.HelloTrpc"), helloImpl) pb.RegisterHiServer(s.Service("trpc.test.helloworld.HelloHttp"), helloImpl) // Alternatively, register the same proto service for all services in the server pb.RegisterHelloServer(s, helloImpl) } ``` -------------------------------- ### Example Curl Command to Query Span Details (Shell) Source: https://github.com/trpc-group/trpc-go/blob/main/rpcz/README.md An example command using curl to perform an HTTP GET request to the RPCZ endpoint to retrieve details for a specific span ID (6673650005084645130). ```shell curl http://ip:port/cmds/rpcz/spans/6673650005084645130 ``` -------------------------------- ### Basic tRPC-Go Server YAML Configuration Source: https://github.com/trpc-group/trpc-go/blob/main/docs/basics_tutorial.zh_CN.md Provides a minimal `trpc_go.yaml` configuration snippet demonstrating how to define a server service, specifying its name, listening IP, port, and protocol. ```yaml server: # 服务端配置 service: # 可以配置多个 service - name: helloworld # 服务名 ip: 127.0.0.1 # 服务监听的 IP port: 8000 # 服务监听的端口 protocol: trpc # 服务使用的协议 ``` -------------------------------- ### Full Mutual TLS Example in Go Test Function Source: https://github.com/trpc-group/trpc-go/blob/main/http/README.md A comprehensive test function demonstrating the setup of a trpc-go server and client with mutual TLS authentication using `server.WithTLS` and `client.WithTLS`. Includes service registration, listener setup, and client proxy creation. ```go func TestHTTPSUseClientVerify(t *testing.T) { const ( network = "tcp" address = "127.0.0.1:0" ) ln, err := net.Listen(network, address) require.Nil(t, err) defer ln.Close() serviceName := "trpc.app.server.Service" + t.Name() service := server.New( server.WithServiceName(serviceName), server.WithNetwork("tcp"), server.WithProtocol("http_no_protocol"), server.WithListener(ln), server.WithTLS( "../testdata/server.crt", "../testdata/server.key", "../testdata/ca.pem", ), ) thttp.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) error { w.Write([]byte(t.Name())) return nil }) thttp.RegisterNoProtocolService(service) s := &server.Server{} s.AddService(serviceName, service) go s.Serve() defer s.Close(nil) time.Sleep(100 * time.Millisecond) c := thttp.NewClientProxy( serviceName, client.WithTarget("ip://"+ln.Addr().String()), ) req := &codec.Body{} rsp := &codec.Body{} require.Nil(t, c.Post(context.Background(), "/", req, rsp, client.WithCurrentSerializationType(codec.SerializationTypeNoop), client.WithSerializationType(codec.SerializationTypeNoop), client.WithCurrentCompressType(codec.CompressTypeNoop), client.WithTLS( "../testdata/client.crt", "../testdata/client.key", "../testdata/ca.pem", "localhost", ), )) require.Equal(t, []byte(t.Name()), rsp.Data) } ``` -------------------------------- ### Manage Default Logger Functions in tRPC-Go Source: https://github.com/trpc-group/trpc-go/blob/main/log/README.zh_CN.md Shows the function signatures for managing the default tRPC-Go logger. This includes functions to retrieve a logger by name (`Get`), set a different logger as the default (`SetLogger`), and get or set the log level for a specific output writer of the default logger (`SetLevel`, `GetLevel`). ```Go // 通过名称获取 Logger func Get(name string) Logger // 设置指定 Logger 为默认 Logger func SetLogger(logger Logger) // 设置默认 Logger 下指定 writer 的日志级别,output 为 writer 数组下标 "0" "1" "2" func SetLevel(output string, level Level) // 获取默认 Logger 下指定 writer 的日志级别,output 为 writer 数组下标 "0" "1" "2" func GetLevel(output string) Level ``` -------------------------------- ### Defining a Basic Protobuf Service Source: https://github.com/trpc-group/trpc-go/blob/main/docs/basics_tutorial.zh_CN.md Demonstrates the basic syntax for declaring a service named `MyService` within a protobuf file, serving as the foundation for defining RPC methods. ```protobuf service MyService { // ... } ``` -------------------------------- ### Getting a Connection from tRPC-Go Pool in Go (Client Example) Source: https://github.com/trpc-group/trpc-go/blob/main/pool/connpool/README.zh_CN.md Demonstrates how a client transport layer might obtain a connection from the pool using the `pool.Get` method. It shows how to configure `GetOptions` with context, framer builder, TLS settings, local address, dial timeout, and protocol before calling `Get`. ```Go // Get getOpts := connpool.NewGetOptions() getOpts.WithContext(ctx) getOpts.WithFramerBuilder(opts.FramerBuilder) getOpts.WithDialTLS(opts.TLSCertFile, opts.TLSKeyFile, opts.CACertFile, opts.TLSServerName) getOpts.WithLocalAddr(opts.LocalAddr) getOpts.WithDialTimeout(opts.DialTimeout) getOpts.WithProtocol(opts.Protocol) conn, err = opts.Pool.Get(opts.Network, opts.Address, getOpts) ``` -------------------------------- ### Generated tRPC-Go Client Proxy Interface and Constructor Source: https://github.com/trpc-group/trpc-go/blob/main/docs/basics_tutorial.zh_CN.md Illustrates the generated Go code for a tRPC-Go client proxy, including the `GreeterClientProxy` interface defining the RPC methods and the `NewGreeterClientProxy` function used to create client instances. ```go type GreeterClientProxy interface { Hello(ctx context.Context, req *HelloReq, opts ...client.Option) (rsp *HelloRsp, err error) } var NewGreeterClientProxy = func(opts ...client.Option) GreeterClientProxy { return &GreeterClientProxyImpl{client: client.DefaultClient, opts: opts} } ``` -------------------------------- ### Registering Multiple Services in tRPC-Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/overview.zh_CN.md Go code snippet showing how to create a tRPC server instance and register multiple distinct services (`Greeter` and `Hello`) by specifying their respective naming service names when calling `s.Service()`. ```go func main() { // 通过读取框架配置中的 server.service 配置项,创建 Naming Service s := trpc.NewServer() // 注册 Greeter 服务 pb.RegisterGreeterService(s.Service("trpc.test.helloworld.Greeter"), &greeterServerImpl{}) // 注册 Hello 服务 pb.RegisterHelloService(s.Service("trpc.test.helloworld.Hello"), &helloServerImpl{}) ... } ``` -------------------------------- ### Generated tRPC-Go Server Service Interface and Registration Source: https://github.com/trpc-group/trpc-go/blob/main/docs/basics_tutorial.zh_CN.md Shows the generated Go code for the server side, including the `GreeterService` interface that user implementations must satisfy and the `RegisterGreeterService` function used to register the implementation with the tRPC-Go framework. ```go type GreeterService interface { Hello(ctx context.Context, req *HelloReq) (*HelloRsp, error) } func RegisterGreeterService(s server.Service, svr GreeterService) { /* ... */ } ``` -------------------------------- ### Implementing and Registering Pass-through Server in tRPC-Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/reverse_proxy.md Provides an example implementation (AccessServerImpl) for the pass-through server's Forward method and demonstrates how to initialize a tRPC server (trpc.NewServer) with the server.WithCurrentSerializationType(codec.SerializationTypeNoop) option to disable serialization, then registers the service and starts the server. ```Go type AccessServerImpl struct{} // Forward implements forwarding proxy logic func (s *AccessServerImpl) Forward(ctx context.Context, reqbody *codec.Body) (rspbody *codec.Body, err error) { // Your own internal processing logic } func main() { s := trpc.NewServer( server.WithCurrentSerializationType(codec.SerializationTypeNoop). ) // No serialization RegisterAccessService(s, &AccessServerImpl{}) if err := s.Serve(); err ! = nil { panic(err) } } ``` -------------------------------- ### Implementing and Registering IDL-based tRPC Service in Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/overview.zh_CN.md This Go snippet shows the implementation of the Greeter service defined in the Protobuf IDL. It includes a SayHello method that handles incoming requests. The main function demonstrates how to create a new tRPC server instance (which reads the Naming Service configuration) and register the implemented Greeter service instance with it. ```Go type greeterServerImpl struct{} // 接口处理函数 func (s *greeterServerImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{ Msg: "Hello, I am tRPC-Go server." }, nil } func main() { // 通过读取框架配置中的 server.service 配置项,创建 Naming Service s := trpc.NewServer() // 注册 Proto Service 的实现实例到 Naming Service 中 pb.RegisterGreeterService(s, &greeterServerImpl{}) // ... } ``` -------------------------------- ### Implementing and Registering tRPC-Go Service (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/server/README.zh_CN.md Presents a Go implementation of the `hello` service's `SayHello` method and demonstrates two ways to register this implementation with a tRPC-Go server: registering the same implementation for specific logical services or registering it globally for all services on the server instance. ```Go type helloImpl struct{} func (s *helloImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { rsp := &pb.HelloReply{} // implement business logic here ... return rsp, nil } func main() { s := trpc.NewServer() // 推荐:为每个 service 单独注册 proto service pb.RegisterHiServer(s.Service("trpc.test.helloworld.HelloTrpc"), helloImpl) pb.RegisterHiServer(s.Service("trpc.test.helloworld.HelloHttp"), helloImpl) // 第二种方式,为 server 中的所有 service 注册同一个 proto service pb.RegisterHelloServer(s, helloImpl) } ``` -------------------------------- ### trpc.GoAndWait Function Signature in Go Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/client/overview.md Provides the function signature for `trpc.GoAndWait`, a utility designed for safer multi-concurrency calls. It starts multiple goroutines, waits for all of them to complete, and includes automatic recovery. It returns the first non-nil error encountered among the concurrent operations. ```Go // GoAndWait encapsulates a safer multi-concurrency call, starts a goroutine and waits for all processing flows to complete, and automatically recovers. // Return value error: the first non-nil error returned in the multi-concurrency goroutine. func GoAndWait(handlers ...func() error) error ``` -------------------------------- ### Example: trpc-go HTTPS Server/Client with Skip Client Verify Source: https://github.com/trpc-group/trpc-go/blob/main/http/README.md A complete Go test function demonstrating how to set up a trpc-go server and client with HTTPS, specifically configuring the client to skip server certificate verification. It includes server setup with TLS and client calls with the corresponding TLS options. ```Go func TestHTTPSSkipClientVerify(t *testing.T) { const ( network = "tcp" address = "127.0.0.1:0" ) ln, err := net.Listen(network, address) require.Nil(t, err) defer ln.Close() serviceName := "trpc.app.server.Service" + t.Name() service := server.New( server.WithServiceName(serviceName), server.WithNetwork("tcp"), server.WithProtocol("http_no_protocol"), server.WithListener(ln), server.WithTLS( "../testdata/server.crt", "../testdata/server.key", "", ), ) thttp.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) error { w.Write([]byte(t.Name())) return nil }) thttp.RegisterNoProtocolService(service) s := &server.Server{} s.AddService(serviceName, service) go s.Serve() defer s.Close(nil) time.Sleep(100 * time.Millisecond) c := thttp.NewClientProxy( serviceName, client.WithTarget("ip://"+ln.Addr().String()), ) req := &codec.Body{} rsp := &codec.Body{} require.Nil(t, c.Post(context.Background(), "/", req, rsp, client.WithCurrentSerializationType(codec.SerializationTypeNoop), client.WithSerializationType(codec.SerializationTypeNoop), client.WithCurrentCompressType(codec.CompressTypeNoop), client.WithTLS( "", "", "none", "", ), )) require.Equal(t, []byte(t.Name()), rsp.Data) } ``` -------------------------------- ### Initializing tRPC Server for Plugin Setup (Go) Source: https://github.com/trpc-group/trpc-go/blob/main/config/README.md This snippet shows the essential call to `trpc.NewServer()`. This function is crucial because it initializes the tRPC server and its plugin system, including configuration data source plugins. All subsequent operations to read business configuration must be performed after this initialization step is complete. ```Go import ( trpc "trpc.group/trpc-go/trpc-go" ) // Plugin system will be initialized when the server is instantiated, and all configuration read operations need to be performed after this. trpc.NewServer() ``` -------------------------------- ### Enable Trace Logging via Environment Variable in tRPC-Go Source: https://github.com/trpc-group/trpc-go/blob/main/log/README.zh_CN.md Provides a shell command example demonstrating how to enable the `trace` log level for a tRPC-Go server by setting the `TRPC_LOG_TRACE` environment variable to `1` before executing the server binary. This method requires the logger configuration to allow `debug` or `trace` level output. ```Shell export TRPC_LOG_TRACE=1 ./server -conf path/to/trpc_go.yaml ``` -------------------------------- ### Running the trpc-go Client Source: https://github.com/trpc-group/trpc-go/blob/main/docs/user_guide/server/flatbuffers.zh_CN.md Shows the shell command to execute the client application using `go run` from its location within the generated project structure. ```sh $ go run cmd/client/main.go ``` -------------------------------- ### Example trpc-go Server Output (Text) Source: https://github.com/trpc-group/trpc-go/blob/main/examples/features/selector/README.md Example log output from the trpc-go server showing a received request. ```text 2023-05-25 16:39:45.765 DEBUG common/common.go:21 recv req:msg:"trpc-go-client"\n2023-05-25 16:39:45.766 DEBUG common/common.go:39 SayHi recv req:msg:"trpc-go-client" ```