-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrpcServer.go
68 lines (56 loc) · 1.65 KB
/
GrpcServer.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
67
68
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"net"
"nrxen.com/dbdriver/protogo"
"os"
)
var server *grpc.Server = nil
//Server is the configuration for the grpc server
type GrpcConfig struct {
host string
port int
}
//An abstraction of the server, allowing to attach the grpc call functions
type GrpcDBServer struct {
}
//override the interface functions (in server .pb.go)
func (s *GrpcDBServer) Get(ctx context.Context, in *dbdriver.GetCmdIn) (*dbdriver.GetCmdOut, error) {
fmt.Printf("Get Key : %s \n", in.Key)
str, err := callGet(in.Key)
if err != nil {
fmt.Println(err)
return &dbdriver.GetCmdOut{Key: in.Key, Value: ""}, fmt.Errorf("not found")
}
return &dbdriver.GetCmdOut{Key: in.Key, Value: str}, nil
}
//override the interface functions (in server.pb.go)
func (s *GrpcDBServer) Set(ctx context.Context, in *dbdriver.SetCmdIn) (*dbdriver.SetCmdOut, error) {
fmt.Printf("Set Key: %s , Value : %s \n", in.Key, in.Value)
return &dbdriver.SetCmdOut{Err: false}, nil
}
func initGrpcServer(config *Configuration) {
list, err := net.Listen("tcp", fmt.Sprintf(":%d", config.grpc.port))
if err != nil {
fmt.Printf("Failed to create a grpc server with port %s ", fmt.Sprintf(":%d", config.grpc.port))
os.Exit(-1)
}
// create a dummy of the abstracted server struct
s := GrpcDBServer{}
//create a grpc server, that will listen
server := grpc.NewServer()
//register service with the server
dbdriver.RegisterGrpcDBServer(server, &s)
//start listening
if err := server.Serve(list); err != nil {
fmt.Println("Failed to start grpc server")
os.Exit(-1)
}
}
func shutdownGrpcServer() {
if server != nil {
server.Stop()
}
}