proto
syntax = "proto3";
package stream.v1;
option go_package = "goGinT/rpc/stream/v1;streamProto";
message StreamReqData {
string data = 1;
}
message StreamResData {
string data = 1;
}
service Greeter {
rpc GetStream(StreamReqData) returns (StreamResData);
}
server端拦截器
package main
import (
"context"
"fmt"
metadataProto "goGinT/rpc/metadata/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"net"
)
type server struct {
}
func (receiver *server) GetStream(ctx context.Context, req *metadataProto.StreamReqData) (*metadataProto.StreamResData, error) {
return &metadataProto.StreamResData{Data: "111"}, nil
}
func main() {
lis, err := net.Listen("tcp", ":8088")
if err != nil {
fmt.Println(err)
return
}
simpleInterceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
md, _ := metadata.FromIncomingContext(ctx)
for key, value := range md {
fmt.Println(key, value)
}
fmt.Println(req, "一个简单的拦截器")
return handler(ctx, req)
}
opts := grpc.UnaryInterceptor(simpleInterceptor)
s := grpc.NewServer(opts)
metadataProto.RegisterGreeterServer(s, &server{})
err = s.Serve(lis)
if err != nil {
fmt.Println(err)
return
}
}
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/4a1d4627220d28966bbc71efc2cf1a82.png)
客户端拦截器
package main
import (
"context"
"fmt"
metadataProto "goGinT/rpc/metadata/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type PerRPCCredentials struct{}
func (c *PerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"name": "789987",
"sex": "nan",
}, nil
}
func (c *PerRPCCredentials) RequireTransportSecurity() bool {
return false
}
func getStream(c metadataProto.GreeterClient) {
res, err := c.GetStream(context.Background(), &metadataProto.StreamReqData{
Data: "唐诗",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res)
}
func main() {
simpleInterceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
fmt.Println(method)
fmt.Println(req)
fmt.Println("打印完毕, 客户端简易拦截器")
err := invoker(ctx, method, req, reply, cc, opts...)
return err
}
var opts []grpc.DialOption
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
opts = append(opts, grpc.WithUnaryInterceptor(simpleInterceptor))
opts = append(opts, grpc.WithPerRPCCredentials(&PerRPCCredentials{}))
dial, err := grpc.Dial("localhost:8088", opts...)
if err != nil {
fmt.Println(err)
return
}
defer func(dial *grpc.ClientConn) {
err = dial.Close()
if err != nil {
fmt.Println(err)
}
}(dial)
c := metadataProto.NewGreeterClient(dial)
getStream(c)
}
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/be3a1041207a6a9cb5e1615169a549e1.png)