在 http 请求当中我们可以设置 header 用来传递数据,grpc 底层采用 http2 协议也是支持传递数据的,采用的是 metadata。 Metadata 对于 gRPC 本身来说透明, 它使得 client 和 server 能为对方提供本次调用的信息。就像一次 http 请求的 RequestHeader 和 ResponseHeader,http header 的生命周期是一次 http 请求, Metadata 的生命周期则是一次 RPC 调用。在 go 语言中,可以用 grpc.WithPerRPCCredentials 方法来实现。
简单说一下 我的demo吧,一般我们的api有一个login, 会返回token, 然后在请求及其他api的时候 就必须带上这个token。
首先我们创建一个项目文件夹 jwttoken,里面在创建一个api文件夹
1.创建/api/api.proto【为了简单我们没有引入其他的包】
syntax = "proto3";
package api;
service Ping {
rpc Login (LoginRequest) returns (LoginReply) {}
rpc SayHello(PingMessage) returns (PingMessage) {}
}
message LoginRequest{
string username=1;
string password=2;
}
message LoginReply{
string status=1;
string token=2;
}
message PingMessage {
string greeting = 1;
}
2.编译该文件, 我一般习惯在根目录下操作:
protoc -I api/ -I${GOPATH}/src --go_out=plugins=grpc:api api/api.proto
3.编写api/handler.go 可以理解是我们日常服务的具体实现:
package api
import (
"fmt"
"golang.org/x/net/context"
)
// Server represents the gRPC server
type Server struct {
}
func (s *Server) Login(ctx context.Context, in *LoginRequest) (*LoginReply, error) {
fmt.Println("Loginrequest: ", in.Username)
if in.Username == "gavin" && in.Password == "gavin" {
tokenString := CreateToken(in.Usernam