首页 > 其他分享 >Go GRPC之拦截器

Go GRPC之拦截器

时间:2023-02-12 21:12:45浏览次数:41  
标签:拦截器 func err GRPC ctx grpc SayHello context Go

grpc服务端和客户端都提供了interceptor功能,功能类似middleware,很适合在这里处理验证、日志等流程,话不多说直接上代码

1.编写helloworld.proto

 

 并用命令生成相应的go文件,生成的文件内容如下:

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.

package proto

import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7

// GreeterServerClient is the client API for GreeterServer service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GreeterServerClient interface {
SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}

type greeterServerClient struct {
cc grpc.ClientConnInterface
}

func NewGreeterServerClient(cc grpc.ClientConnInterface) GreeterServerClient {
return &greeterServerClient{cc}
}

func (c *greeterServerClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
out := new(HelloReply)
err := c.cc.Invoke(ctx, "/helloworld.GreeterServer/SayHello", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}

// GreeterServerServer is the server API for GreeterServer service.
// All implementations must embed UnimplementedGreeterServerServer
// for forward compatibility
type GreeterServerServer interface {
SayHello(context.Context, *HelloRequest) (*HelloReply, error)
mustEmbedUnimplementedGreeterServerServer()
}

// UnimplementedGreeterServerServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServerServer struct {
}

func (UnimplementedGreeterServerServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}
func (UnimplementedGreeterServerServer) mustEmbedUnimplementedGreeterServerServer() {}

// UnsafeGreeterServerServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServerServer will
// result in compilation errors.
type UnsafeGreeterServerServer interface {
mustEmbedUnimplementedGreeterServerServer()
}

func RegisterGreeterServerServer(s grpc.ServiceRegistrar, srv GreeterServerServer) {
s.RegisterService(&GreeterServer_ServiceDesc, srv)
}

func _GreeterServer_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HelloRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServerServer).SayHello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/helloworld.GreeterServer/SayHello",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServerServer).SayHello(ctx, req.(*HelloRequest))
}
return interceptor(ctx, in, info, handler)
}

// GreeterServer_ServiceDesc is the grpc.ServiceDesc for GreeterServer service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var GreeterServer_ServiceDesc = grpc.ServiceDesc{
ServiceName: "helloworld.GreeterServer",
HandlerType: (*GreeterServerServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SayHello",
Handler: _GreeterServer_SayHello_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "helloworld.proto",
}
2.服务端文件server.go
package main

import (
"OldPacketTest/grpc_test/proto"
"context"
"fmt"
"google.golang.org/grpc"
"net"
)

type Server struct {
proto.UnimplementedGreeterServerServer
}

func (s *Server) SayHello(ctx context.Context, req *proto.HelloRequest) (*proto.HelloReply, error) {
return &proto.HelloReply{
Message: "hello " + req.Name,
}, nil
}

func main() {
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
fmt.Println("接收到了一个新的请求")
return handler(ctx, req)
}
opt := grpc.UnaryInterceptor(interceptor)
g := grpc.NewServer(opt)
proto.RegisterGreeterServerServer(g, &Server{})
lis, err := net.Listen("tcp", "0.0.0.0:8081")
if err != nil {
panic("failed to listen:" + err.Error())
}
err = g.Serve(lis)
if err != nil {
panic("failed to start grpc:" + err.Error())
}
}

3.客户端文件client.go
package main

import (
"OldPacketTest/grpc_test/proto"
"context"
"fmt"
"google.golang.org/grpc"
"time"
)

func main() {
interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
start := time.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
fmt.Printf("耗时:%s\n", time.Since(start))
return err
}
var opts []grpc.DialOption
opts = append(opts, grpc.WithInsecure())
opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
conn, err := grpc.Dial("127.0.0.1:8081", opts...)
if err != nil {
panic(err)
}
defer conn.Close()

c := proto.NewGreeterServerClient(conn)
r, err := c.SayHello(context.Background(), &proto.HelloRequest{
Name: "bobby",
})
if err != nil {
panic(err)
}
fmt.Println(r.Message)
}
 

标签:拦截器,func,err,GRPC,ctx,grpc,SayHello,context,Go
From: https://www.cnblogs.com/lisus2000/p/17114715.html

相关文章

  • Go Grpc的四种流
    srteam顾名思义就是一种流,可以源源不断的推送数据,很适合传输一些大数据,或者服务端和客户端长时间数据交互,比如客户端可以向服务端订阅一个数据,服务端就......
  • 基于Django开发的小型超市收银系统及各种炒股指标信息
    登录页面注册修改密码诗词推荐背景刷新更换登录 首页今日收益金额日收益折线图商品热度排行商品预警信息今日待办任务诗词推荐      ......
  • Gogs安装
    Gogs环境要求我以rhel6.3为例,已经属于生命周期边缘了#安装gityuminstall-ygitgit--versiongitversion1.7.1#安装mysql-serveryuminstall-ymysql-server......
  • Go语言学习11-数据初始化
    数据初始化书接上篇,我们了解了Go语言的指针类型。那到目前为止,Go的数据类型就差不多介绍完了,下面就是讲解更优雅地对Go数据的初始化了。这里的数据初始化是指对某个......
  • django-channels实际应用
    django实现websocket实时数据推送。应用场景群组/单对单语音聊天页面数据实时推送(后端主导)技术django+channelsdjango>=2channels官方wsgiWeb服务器网关接口(P......
  • Golang:交叉编译到Linux、macOS、windows并运行
    Golang可以直接编译成不同平台的可执行文件,并且直接运行,很方便第三方使用者部署运行项目结构$tree.├──Makefile└──src└──hello.go项目很简单,一个H......
  • python django二手商城(课设、学习、毕设、源码下载)
    pythondjango二手商城pythondjango校园二手商城django校园商城django校园商店django电子商城django网上商城前端:htmlcss等后端:python django数据库:MYSQL涉......
  • Python django酒店旅游推荐系统(课设、学习、毕设、源码下载)
    Pythondjango酒店旅游推荐系统酒店系统酒店推荐系统旅游系统旅游推荐系统技术:Python django数据库:MySQL涉及功能:登录、注册、登出、修改密码、查看个人中心酒......
  • python django 个人电影网项目(课设、学习、毕设、源码下载)
    pythondjango个人电影网项目pythondjango电影推荐网pythondjango电影网基于pythondjango个人电影网项目该系统详情:后端:python3.6+MySQL5.7+Django框架......
  • Python django 汽车商城(课设、学习、毕设、源码下载)
    Pythondjango汽车商城汽车系统在线商城二手汽车网汽车网站django汽车推荐商城技术:Python  django数据库:MySQL前端:html  css  js涉及功能:登录,注册,登出,......