-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (78 loc) · 2.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
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
package main
import (
basketBallPlayer "basic-gRPC-proto"
"basic-gRPC-server/models"
"context"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
"net"
"time"
"github.com/patrickmn/go-cache"
"google.golang.org/grpc"
)
type server struct{}
var c *cache.Cache
var db *gorm.DB
const dbPath = "host=34.84.26.219 user=postgres password=JPHwcKkIGldw14wm"
func init() {
var e error
db, e = gorm.Open("postgres", dbPath)
defer db.Close()
if e != nil {
panic("failed to connect to database")
}
db.AutoMigrate(&models.BasketballPlayer{})
}
func (*server) GetBasketballPlayer(ctx context.Context, r *basketBallPlayer.PlayerRequest) (*basketBallPlayer.PlayerResponse, error) {
id := r.GetId()
fmt.Println("Checking cache...")
playerVal, found := c.Get(id)
if found {
player := playerVal.(*basketBallPlayer.Player)
return &basketBallPlayer.PlayerResponse{
Result: player,
}, nil
} else {
fmt.Println("Checking database...")
db, e := gorm.Open("postgres", dbPath)
defer db.Close()
if e != nil {
panic(fmt.Sprintf("failed to connect to database: %v", e))
}
var p models.BasketballPlayer
if e = db.First(&p, id).Error; e != nil {
return nil, fmt.Errorf("could not find player with id: %v", id)
} else {
gRPCResult := p.GetgRPCModel()
c.Set(id, &gRPCResult, cache.DefaultExpiration)
return &basketBallPlayer.PlayerResponse{
Result: &gRPCResult,
}, nil
}
}
}
func main() {
fmt.Println("Starting gRPC micro-service...")
c = cache.New(60*time.Minute, 70*time.Minute)
c.Set("1", &basketBallPlayer.Player{
Id: "1",
FirstName: "James",
LastName: "LeBron",
Age: 33,
PhotoUrl: "https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/1610612747/2019/260x190/2544.png",
PointsPerGame: 26,
AssistsPerGame: 11,
ReboundsPerGame: 8,
}, cache.DefaultExpiration)
l, e := net.Listen("tcp", ":50051")
if e != nil {
log.Fatalf("Failed to start listener %v", e)
}
s := grpc.NewServer()
basketBallPlayer.RegisterPlayerServiceServer(s, &server{})
if e := s.Serve(l); e != nil {
log.Fatalf("failed to serve %v", e)
}
}