1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package main
import ( "PackageTest/grpc_interpretor/proto" "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "net" )
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() {
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { fmt.Println("接收到了一个新的请求") md, ok := metadata.FromIncomingContext(ctx) fmt.Println(md) if !ok { fmt.Println("get metadata error") return resp, status.Error(codes.Unauthenticated, "无token认证信息") } var ( appid string appkey string ) if va1, ok := md["appid"]; ok { appid = va1[0] } if va1, ok := md["appkey"]; ok { appkey = va1[0] }
if appid != "23421322" || appkey != "this is key" { return resp, status.Error(codes.Unauthenticated, "无token认证信息") }
res, err := handler(ctx, req) fmt.Println("请求已经完成") return res, err } opt := grpc.UnaryInterceptor(interceptor) g := grpc.NewServer(opt) proto.RegisterGreeterServer(g, &Server{}) lis, err := net.Listen("tcp", "0.0.0.0:8080") if err != nil { panic("failed to listen " + err.Error()) } err = g.Serve(lis) if err != nil { panic("failed to grpc" + err.Error()) } }
|