-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
66 lines (56 loc) · 1.4 KB
/
server.go
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
63
64
65
66
package main
import (
"context"
"github.com/sqjian/go-kit/snippet/grpc/idl"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
"log"
"net"
)
const (
address = "localhost:50051"
)
type server struct{}
func (s *server) SayHello(ctx context.Context, in *idl.HelloRequest) (*idl.HelloReply, error) {
return &idl.HelloReply{Message: "Hello " + in.Name}, nil
}
func auth(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Errorf(codes.Unauthenticated, "无Token认证信息")
}
var (
key string
)
if val, ok := md["key"]; ok {
key = val[0]
}
if key != "i am key" {
return status.Errorf(codes.Unauthenticated, "Token认证信息无效: key =%s", key)
}
return nil
}
func interceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
err := auth(ctx)
if err != nil {
return nil, err
}
return handler(ctx, req)
}
func main() {
lis, err := net.Listen("tcp", address)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
opts = append(opts, grpc.UnaryInterceptor(interceptor))
s := grpc.NewServer(opts...)
idl.RegisterGreeterServer(s, &server{})
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}