当前位置:网站首页>go grpc custom interceptor
go grpc custom interceptor
2022-07-30 01:52:00 【give me a bottle of ice kuoluo】
proto file
syntax = "proto3";import "google/protobuf/timestamp.proto";package pb;option go_package = "./pb";serviceToDoService {rpc DoWork (TodoRequest) returns (TodoResponse);}enum Week {Sunday = 0;Monday = 1;Tuesday = 2;Wednesday = 3;Thursday = 4;Friday = 5;Saturday = 6;}message TodoRequest{string todo = 1;Week week = 2;map bookMap = 3; // BookMap map[string]stringgoogle.protobuf.Timestamp doneTime = 4;}message TodoResponse {bool done = 1;} Generate grpc file
protoc user.proto --go_out=./ --go-grpc_out=./ --go-grpc_opt=require_unimplemented_servers=falseServer
package mainimport ("context""fmt""google.golang.org/grpc""google.golang.org/grpc/codes""google.golang.org/grpc/metadata""google.golang.org/grpc/status""grpc_enum/pb""net""time")//custom interceptorfunc MyInterceptor (ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){// get data from contextmd, ok := metadata.FromIncomingContext(ctx)if !ok {fmt.Println("Interceptor: metadata nil")return nil,status.Error(codes.Unauthenticated, "Authentication failed [metadata]")}token , ok := md["token"]if !ok {fmt.Println("Interceptor: token nil")return nil,status.Error(codes.Unauthenticated, "Authentication failed [token]")}fmt.Println("token:",token)now := time.Now()resp, err = handler(ctx, req) //The previous one is executed first; the following last execution is similar to the next() middleware in ginfmt.Println("req:",req)lastTime := time.Now().Sub(now)fmt.Println("Execution time: ",lastTime.Milliseconds())return}type TodoInfo struct{}func (t *TodoInfo)DoWork(ctx context.Context, td_req *pb.TodoRequest) (*pb.TodoResponse, error) {//Accept the context parametermd, ok := metadata.FromIncomingContext(ctx)if !ok {fmt.Println("metadata false")}for k,v := range md {fmt.Println("k:",k,"== v:",v)}fmt.Println(td_req.Todo)fmt.Println(td_req.Week)return &pb.TodoResponse{Done: true,}, nil}func main() {//register interceptorserviceOption := grpc.UnaryInterceptor(MyInterceptor)//Instantiate grpcgrpcServer := grpc.NewServer(serviceOption)// register servicepb.RegisterToDoServiceServer(grpcServer,&TodoInfo{})listen,err := net.Listen("tcp", "127.0.0.1:8081")if err != nil {panic(err)}err = grpcServer.Serve(listen)if err != nil {println(err)}}Client
package mainimport ("context""fmt""google.golang.org/grpc""google.golang.org/grpc/metadata""grpc_enum/pb")//Inherit PerRPCCredentials to implement authentication//Override GetRequestMetadata and RequireTransportSecuritytype MyCredentials struct{}func (c *MyCredentials)GetRequestMetadata(ctx context.Context, uri ...string)(map[string]string, error){return map[string]string{"token":"123456897",}, nil}func (c *MyCredentials)RequireTransportSecurity()bool{return false}func main() {//interceptor//clientInterceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error{// md2 := metadata.Pairs("token","99663322poiopui")// ctx = metadata.NewOutgoingContext(context.Background(), md2)//// now := time.Now()// err := invoker(ctx, method, req, reply, cc, opts ...)// lastTime := time.Now().Sub(now)// fmt.Println("Client execution time: ",lastTime.Milliseconds())// return err//}//opt := grpc.WithUnaryInterceptor(clientInterceptor)//authenticationopt := grpc.WithPerRPCCredentials(&MyCredentials{})conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure(), opt)defer conn.Close()if err != nil {panic(err)}//Instantiate the ToDo serviceclient := pb.NewToDoServiceClient(conn)md1 := metadata.New(map[string]string{"name" : "hello grpc",})// pass parameters from contextctx := metadata.NewOutgoingContext(context.Background(), md1)//Call the server-side DoWork methodrep, err := client.DoWork(ctx,&pb.TodoRequest{Todo: "Interceptor",Week: pb.Week_Monday,BookMap: map[string]string{"age" : "20",},//DoneTime: time.Now(),})if err != nil {panic(err)}fmt.Println("rep:",rep)}边栏推荐
猜你喜欢

OSPF shamlink 解决后门链路问题

Fabric Writing Case Chaincode

经济衰退时期的对比:如今更像历史上的哪段时期?

Type-C边充电边OTG芯片——LDR6028A

CVPR 2022 Best Paper -- Learning to Solve Hard Minimal Problems

JS develops 3D modeling software

【内部资源】冲击年薪30W+的软件测试人员,这份资料必须领取

fluttter学习之ButtonStyle 、MaterialStateProperty

ButtonStyle, MaterialStateProperty learned by flutter

exness: U.S. GDP shrinks, yen bounces back
随机推荐
exness: U.S. GDP shrinks, yen bounces back
js中原型链的理解,原型链解决的是什么问题?
Fabric Private Data Case
mysql error is too long for user name (should be no longer than 16)
STM32L4R9ZIY6PTR STM32L4高性能嵌入式—MCU
It is really strong to apply the @Transactional transaction annotation to such perfection!
机械设备制造企业如何借助ERP系统,解决成本核算难题?
基于蒙特卡诺的风场景模型出力(Matlab代码实现)
OSPF shamlink 解决后门链路问题
Sublime does background transparency and column editor
RAII技术学习
Google浏览器打开axure产品原型的解决方案
What majors become more popular the older they get?
不要急,没有一朵花,从一开始就是花,也不要嚣张,没有一朵花,
十一、uni-app生成弹窗及换行
多AZ双活容灾部署的云端系统架构设计说明书框架
JS开发3D建模软件
MPLS VPN跨域-optionC2
tcp ip
Leetcode70. 爬楼梯