trpc.group/trpc-go/trpc-go@v1.0.3/docs/user_guide/client/flatbuffers.md (about) 1 English | [中文](flatbuffers.zh_CN.md) 2 3 # Introduction 4 5 This section shows how to call flatbuffers services in tRPC-Go. 6 7 # Principles 8 9 See [tRPC-Go builds flatbuffers service](/docs/user_guide/server/flatbuffers.zh_CN.md). 10 11 # 示例 12 13 In examples from [tRPC-Go builds flatbuffers service](/docs/user_guide/server/flatbuffers.zh_CN.md), we can generate the client. The project structure is as follows: 14 15 ```shell 16 ├── cmd/client/main.go # client 17 ├── go.mod 18 ├── go.sum 19 ├── greeter_2.go # second service implementation 20 ├── greeter_2_test.go # test for second service implementation 21 ├── greeter.go # first service implementation 22 ├── greeter_test.go # test for first service implementation 23 ├── main.go # service startup 24 ├── stub/github.com/trpcprotocol/testapp/greeter # stub code 25 └── trpc_go.yaml # configuration file 26 ``` 27 28 Refer to `cmd/client/main.go` for client code. Here is an example for single-send and single-receive: 29 30 ```go 31 package main 32 33 import ( 34 "flag" 35 "io" 36 37 flatbuffers "github.com/google/flatbuffers/go" 38 39 trpc "trpc.group/trpc-go/trpc-go" 40 "trpc.group/trpc-go/trpc-go/client" 41 "trpc.group/trpc-go/trpc-go/log" 42 fb "github.com/trpcprotocol/testapp/greeter" 43 ) 44 45 func callGreeterSayHello() { 46 proxy := fb.NewGreeterClientProxy( 47 client.WithTarget("ip://127.0.0.1:8000"), 48 client.WithProtocol("trpc"), 49 ) 50 ctx := trpc.BackgroundContext() 51 // Single-send single-receive client usage 52 b := flatbuffers.NewBuilder(clientFBBuilderInitialSize) 53 // Add field 54 // Replace "String" in "CreateString" with the type of the field 55 // Replace "Message" in "AddMessage" with the name of the field 56 // i := b.CreateString("GreeterSayHello") 57 fb.HelloRequestStart(b) 58 // fb.HelloRequestAddMessage(b, i) 59 b.Finish(fb.HelloRequestEnd(b)) 60 reply, err := proxy.SayHello(ctx, b) 61 if err != nil { 62 log.Fatalf("err: %v", err) 63 } 64 // Replace "Message" with the name of the field 65 // log.Debugf("simple rpc receive: %q", reply.Message()) 66 log.Debugf("simple rpc receive: %v", reply) 67 } 68 69 // clientFBBuilderInitialSize set initial client-side size for flatbuffers.NewBuilder 70 var clientFBBuilderInitialSize int 71 72 func init() { 73 flag.IntVar(&clientFBBuilderInitialSize, "n", 1024, "set client flatbuffers builder's initial size") 74 } 75 76 func main() { 77 flag.Parse() 78 callGreeterSayHello() 79 } 80 ``` 81 82 The structure is similar to protobuf, where `"github.com/trpcprotocol/testapp/greeter"` is the importpath for stubs. Refer to protobuf for managing stubs. 83 84 Above is pure client-side implementation. When using client in a service, downstream services can be set in `trpc_go.yaml`, and no longer needing the code below: 85 86 ```go 87 proxy := fb.NewGreeterClientProxy( 88 client.WithTarget("ip://127.0.0.1:8000"), 89 client.WithProtocol("trpc"), 90 ) 91 ```