hello.proto
syntax = "proto3";
option go_package ="./;proto";
service Server {
rpc SayHello(HelloReq) returns (HelloRes);
}
message HelloReq{
string name = 1;
}
message HelloRes{
string msg = 1;
}
proto生成go文件命令
protoc --go_out=. --go-grpc_out=. hello.proto
client.go
方法一:自定义拦截器,实现统一参数校验
package main
import (
"Go_Bible/grpc_token_auth_test/proto"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func main() {
authInterceptor := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
md := metadata.New(map[string]string{
"appid": "10010",
"access_key": "1234",
})
ctx = metadata.NewOutgoingContext(ctx, md)
err := invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
fmt.Println("客户端接口调用错误-->" + err.Error())
}
return err
}
op