-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
63 lines (51 loc) · 1.14 KB
/
main.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
package main
import (
"context"
"log"
"net"
"sync"
pb "github.com/shayanh/grpc-go-contracts/examples/mynote/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
port = ":8001"
)
type user struct {
userID int
token string
}
type authServiceServer struct {
pb.UnimplementedAuthServiceServer
mutex sync.Mutex
users []*user
}
var authService authServiceServer
func init() {
authService.mutex.Lock()
defer authService.mutex.Unlock()
authService.users = []*user{
{userID: 0, token: "some-token-0"},
{userID: 1, token: "some-token-1"},
}
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer()
pb.RegisterAuthServiceServer(s, &authService)
if err := s.Serve(lis); err != nil {
log.Fatal(err)
}
}
func (as *authServiceServer) Authenticate(ctx context.Context, in *pb.AuthenticateRequest) (*pb.AuthenticateResponse, error) {
for _, user := range as.users {
if user.token == in.Token {
return &pb.AuthenticateResponse{UserId: int32(user.userID)}, nil
}
}
return nil, status.Error(codes.Unauthenticated, "invalid token")
}