web-dev-qa-db-ja.com

サーバー側のgrpcでメタデータを読み取る方法は? (golangの例)

Grpcでサーバー側のメタデータ(ヘッダーとして渡される)を読み取る方法は? golangの例はありますか?

私はこのようなものを書いています:

// this should be passed from the client side as a context and needs to accessed on server side to read the metadata
var headers = metadata.New(map[string]string{"authorization": "", "space":  "", "org": "", "limit": "", "offset": ""})

承認トークンを検証関数に渡して、受信したトークンを検証したいと思います。

func validate_token(ctx context.Context, md *metadata.MD) (context.Context, error){
    token := headers["authorization"]
}
7
Sanket

サーバーを呼び出す前に、メタデータをクライアントのコンテキストに挿入する必要があります。

単項RPCの場合、クライアント側は次のようになります。

conn, _ := grpc.Dial(address, opts...)
client := NewMyClient(conn) // generated from your proto with the grpc protoc option

header := metadata.New(map[string]string{"authorization": "", "space":  "", "org": "", "limit": "", "offset": ""})
// this is the critical step that includes your headers
ctx := metadata.NewContext(context.Background(), header)

request := // construct a request for your service
response, err := client.MyMethod(ctx, request)

ストリームの場合、ほとんど同じように見えます。

conn, _ := grpc.Dial(address, opts...)
client := NewMyClient(conn) // generated from your proto with the grpc protoc option

header := metadata.New(map[string]string{"authorization": "", "space":  "", "org": "", "limit": "", "offset": ""})
// this is the critical step that includes your headers
ctx := metadata.NewContext(context.Background(), header)
stream, err := client.MyMethodStream(ctx)

for {
    request :=  // construct a request for your service
    err := stream.Send(request)
    response := new(Response)
    err = stream.RecvMsg(response)
}

単項RPCのサーバー側:

func (s myServer) MyMethod(context.Context, *Request) (*Response, error) {
    headers, ok := metadata.FromContext(ctx)
    token := headers["authorization"]
}

ストリーミングRPCの場合:

func (s myServer) MyMethodStream(stream MyMethod_MyServiceStreamServer) error {
    headers, ok := metadata.FromContext(stream.Context())
    token := headers["authorization"]
    for {
        request := new(Request)
        err := stream.RecvMsg(request)
        // do work
        err := stream.SendMsg(response)
    }
}

ストリームの場合、ヘッダーを送信できるのは3回だけであることに注意してください。最初のストリームを開くために使用されるコンテキストでは、 grpc.SendHeader および grpc.SetTrailer を介して。ストリーム内の任意のメッセージにヘッダーを設定することはできません。単項RPCヘッダーはすべてのメッセージとともに送信され、grpc.SendHeaderと grpc.SetHeader 、およびgrpc.SetTrailerを使用して初期コンテキストで設定できます。

21
Zack Butcher