当前位置:网站首页>go grpc 自定义拦截器
go grpc 自定义拦截器
2022-07-30 01:39:00 【给我一瓶冰阔洛】
proto文件
syntax = "proto3";
import "google/protobuf/timestamp.proto";
package pb;
option go_package = "./pb";
service ToDoService {
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 <string,string> bookMap = 3; // BookMap map[string]string
google.protobuf.Timestamp doneTime = 4;
}
message TodoResponse {
bool done = 1;
}
生成grpc文件
protoc user.proto --go_out=./ --go-grpc_out=./ --go-grpc_opt=require_unimplemented_servers=false服务端
package main
import (
"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"
)
//自定义拦截器
func MyInterceptor (ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){
//从context 获取数据
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
fmt.Println("拦截器 :metadata nil")
return nil,status.Error(codes.Unauthenticated, "认证失败[metadata]")
}
token , ok := md["token"]
if !ok {
fmt.Println("拦截器 :token nil")
return nil,status.Error(codes.Unauthenticated, "认证失败[token]")
}
fmt.Println("token:",token)
now := time.Now()
resp, err = handler(ctx, req) //前面的先执行; 下面的最后执行类似gin 中 next() 中间件
fmt.Println("req:",req)
lastTime := time.Now().Sub(now)
fmt.Println("执行时间:",lastTime.Milliseconds())
return
}
type TodoInfo struct{
}
func (t *TodoInfo)DoWork(ctx context.Context, td_req *pb.TodoRequest) (*pb.TodoResponse, error) {
//接受context 参数
md, 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() {
//注册拦截器
serviceOption := grpc.UnaryInterceptor(MyInterceptor)
//实例化grpc
grpcServer := grpc.NewServer(serviceOption)
//注册服务
pb.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)
}
}
客户端
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"grpc_enum/pb"
)
//继承PerRPCCredentials 实现认证
//重写GetRequestMetadata 和 RequireTransportSecurity
type 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() {
//拦截器
//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("客户端执行时间:",lastTime.Milliseconds())
// return err
//}
//opt := grpc.WithUnaryInterceptor(clientInterceptor)
//认证
opt := grpc.WithPerRPCCredentials(&MyCredentials{})
conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure(), opt)
defer conn.Close()
if err != nil {
panic(err)
}
//实例化 ToDo 服务
client := pb.NewToDoServiceClient(conn)
md1 := metadata.New(map[string]string{
"name" : "hello grpc",
})
//从过context 传递参数
ctx := metadata.NewOutgoingContext(context.Background(), md1)
//调用服务端DoWork方法
rep, err := client.DoWork(ctx,&pb.TodoRequest{
Todo: "拦截器",
Week: pb.Week_Monday,
BookMap: map[string]string{
"age" : "20",
},
//DoneTime: time.Now(),
})
if err != nil {
panic(err)
}
fmt.Println("rep:",rep)
}
边栏推荐
- Navicat error: 1045-Access denied for user [email protected](using passwordYES)
- LeetCode 2352. 相等行列对
- Running a Fabric Application
- Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE
- ROS 2知识:通信协议 DDS/RTPS
- 数据流图、数据字典
- 经济衰退时期的对比:如今更像历史上的哪段时期?
- 记笔记!电源自动测试系统测试电源纹波详细方法
- 泰克Tektronix示波器软件TDS210|TDS220|TDS224上位机软件NS-Scope
- LeetCode 2342. Digital and equal number of one of the biggest and
猜你喜欢

【Vmware NSX-V基本架构及组件安装】

Recommendation system: collection of user "behavioral data" [use Kafka and Cassandra to process data] [if it overlaps with business data, it also needs to be collected independently]

Meetings OA To Be Meeting && All Meetings

【VMWARE--共享文件】

记笔记!电源自动测试系统测试电源纹波详细方法
![[VMWARE--Shared files]](/img/34/1f1609edc82c0a134886f9bf936f7f.png)
[VMWARE--Shared files]

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

The role of interface testing

Leetcode69. x 的平方根

1.2Recyclerview实现Item点击事件
随机推荐
记笔记!电源自动测试系统测试电源纹波详细方法
把@Transactional事务注解用到如此炉火纯青,真的强!
FlutterBoost 3.0出现 Activity无法转换为ExclusiveAppComponent<Activity>的解决办法
vscode 工作区配置插件 配置不同工作环境
华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
SSM integration case
LeetCode / Scala - 无重复字符最长子串 ,最长回文子串
Sublime does background transparency and column editor
泰克Tektronix示波器软件TDS210|TDS220|TDS224上位机软件NS-Scope
How Junior Testers Grow Fast
[Flutter] Flutter preloading of mixed development solves the problem of slow page loading for the first time
LeetCode 2352. Equal Row Column Pairs
接口测试自动化后起之秀-YApi接口管理平台
Performance Testing Theory 1 | Sorting out difficult problems in performance testing
CMake Tutorial 巡礼(1)_基础的起点
[深入研究4G/5G/6G专题-45]: 5G Link Adaption链路自适应-1-总体架构
What to test for app testing
接口测试的作用
多AZ双活容灾部署的云端系统架构设计说明书框架
1.2Recyclerview实现Item点击事件