1. proto
syntax = "proto3";
option go_package = ".;proto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
2. 服务端
package main
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"net"
"google.golang.org/grpc"
"start/token_interceptor/proto"
)
type Server struct{}
func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply,
error){
return &proto.HelloReply{
Message: "hello "+request.Name,
}, nil
}
func main(){
lis, err := net.Listen("tcp", ":50051")
if err != nil {
fmt.Println(err.Error())
return
}
var interceptor grpc.UnaryServerInterceptor
interceptor = func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return resp, status.Errorf(codes.Unauthenticated, "无Token认证信息")
}
var (
appid string
appkey string
)
if val, ok := md["appid"]; ok {
appid = val[0]
}
if val, ok := md["appkey"]; ok {
appkey = val[0]
}
if appid != "golangblogs" || appkey != "good good study" {
return resp, status.Errorf(codes.Unauthenticated, "Token认证信息无效: appid=%s, appkey=%s", appid, appkey)
}
// 继续处理请求
return handler(ctx, req)
}
var opts []grpc.ServerOption
opts = append(opts, grpc.UnaryInterceptor(interceptor))
s := grpc.NewServer(opts...)
ser :=& Server{}
proto.RegisterGreeterServer(s, ser)
s.Serve(lis)
}
3. 客户端
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"start/token_interceptor/proto"
)
type customCredential struct{}
func (c customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"appid": "golangblogs",
"appkey": "good good study",
}, nil
}
func (c customCredential) RequireTransportSecurity() bool {
return false
}
func main() {
var opts []grpc.DialOption
//opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
opts = append(opts, grpc.WithInsecure())
opts = append(opts, grpc.WithPerRPCCredentials(new(customCredential)))
// 指定客户端interceptor
conn, err := grpc.Dial("localhost:50051", opts...)
if err != nil {
panic(err)
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
//rsp, _ := c.Search(context.Background(), &empty.Empty{})
rsp, err := c.SayHello(context.Background(), &proto.HelloRequest{
Name: "叶良辰",
})
if err != nil {
panic(err)
}
fmt.Println(rsp.Message)
}