trpc.group/trpc-go/trpc-go@v1.0.3/docs/user_guide/metadata_transmission.md (about) 1 English | [中文](metadata_transmission.zh_CN.md) 2 3 # tRPC-Go metadata transmission 4 5 ## Introduction 6 7 Metadata transparent transmission: The framework supports transparent transmission of metadata between the client and server, and automatically transmits them throughout the entire call chain. The metadata is actually key-value pairs, where the key is of `string` type and the value is of `[]byte` type. The value can be any data. It provides additional information about the RPC request. The framework passes metadata through `context`. 8 9 The following document describes how to use metadata transparent transmission in the framework. 10 11 ## Principle and Implementation 12 13 tRPC-Go transmits metadata through the transinfo field in the tRPC protocol header. You should set the metadata that need to be transmitted through the framework's API to the context. When the framework encodes request, it sets the metadata from user to the transinfo field of the protocol, and then transmits them. On the other side, the framework will parse metadata from the transinfo field when decods response, and you can obtain the metadata from the context. 14 15 ## Example 16 17 #### Client transmits data to server 18 19 When the client sends a request, you can set the metadata by adding options. You can add multiple metadata. 20 21 ```go 22 options := []client.Option{ 23 client.WithMetaData("key1", []byte("val1")), 24 client.WithMetaData("key2", []byte("val2")), 25 client.WithMetaData("key3", []byte("val3")), 26 } 27 28 rsp, err := proxy.SayHello(ctx, options...) // Note: ctx should be passed by the framework 29 ``` 30 31 The downstream server can obtain the metadata from the client through the framework's `ctx`. 32 33 ```go 34 // Note: Use the ctx passed by the framework. 35 // The client sets the value of key1 to val1, so the value will be val1. 36 // If the client does not set the value for key1, an empty data will be returned. 37 trpc.GetMetaData(ctx, "key1") 38 ``` 39 40 #### Server transmits data to client 41 42 When the server responds to the client, it can set the metadata through `ctx` to the upstream client. 43 44 ```go 45 // Note: Use the ctx passed by the framework. 46 // Set the value of the metadat key1 to []byte("val1") through this API. 47 trpc.SetMetaData(ctx, "key1", []byte("val1")) 48 ``` 49 50 The upstream client can obtain it by setting the response head of each protocol. 51 52 ```go 53 head := &trpc.ResponseProtocol{} 54 options := []client.Option{ 55 client.WithRspHead(head), 56 } 57 58 rsp, err := proxy.SayHello(ctx, options...) // Note: use ctx passed by the framework 59 head.TransInfo // metadata transmitted by the framework 60 ```