-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (68 loc) · 1.68 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"os/signal"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"google.golang.org/grpc"
product "github.com/anatollupacescu/kong-grpc-lb/internal"
"github.com/anatollupacescu/kong-grpc-lb/proto"
)
var (
products *mongo.Collection
mongoCtx context.Context
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
mongoCtx = context.Background()
mongoURL, exists := os.LookupEnv("MONGODB_URL")
if !exists { // default for local run
mongoURL = "mongodb://localhost:27017"
}
db, err := mongo.Connect(mongoCtx, options.Client().ApplyURI(mongoURL))
if err != nil {
return fmt.Errorf("connect to mongo: %v", err)
}
log.Printf("ping mongo at URL: %v\n", mongoURL)
if err := db.Ping(mongoCtx, nil); err != nil {
return fmt.Errorf("ping mongo: %v", err)
}
products = db.Database("price").Collection("product")
listener, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("unable to listen on port :50051: %v", err)
}
s := grpc.NewServer()
proto.RegisterProductServiceServer(s, &ProductServiceServer{
App: product.App{ProductDB: products},
})
go func() {
log.Println("starting server on port :50051...")
if err := s.Serve(listener); err != nil {
log.Fatalf("serve rpc: %v", err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
log.Println("\nstopping the server...")
s.Stop()
if err := listener.Close(); err != nil {
return err
}
log.Println("closing db connection")
err = db.Disconnect(mongoCtx)
log.Println("done")
return err
}