-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
103 lines (84 loc) · 2.44 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
97
98
99
100
101
102
103
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/go-kit/kit/log"
"github.com/hoop33/roster/pb"
"github.com/hoop33/roster/players"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"google.golang.org/grpc"
)
func main() {
logger := createLogger()
startLogger := log.With(logger, "tag", "start")
startLogger.Log("msg", "created logger")
db, err := createDatabase()
if err != nil {
startLogger.Log("msg", "failed to connect to database", "err", err)
os.Exit(1)
}
defer db.Close()
startLogger.Log("msg", "connected to database")
ps := createPlayersService(db, logger)
startLogger.Log("msg", "created players service")
ep := players.NewEndpoints(ps)
startLogger.Log("msg", "created endpoints")
errs := make(chan error)
go func() {
httpTransport := players.NewHTTPTransport(ep, logger)
startLogger.Log("msg", "created http transport")
httpAddr := ":9090"
startLogger.Log("transport", "http", "address", httpAddr, "msg", "listening")
errs <- http.ListenAndServe(httpAddr, httpTransport)
}()
go func() {
grpcTransport := players.NewGRPCTransport(ep, logger)
startLogger.Log("msg", "created grpc transport")
grpcAddr := ":9091"
listener, err := net.Listen("tcp", grpcAddr)
if err != nil {
errs <- err
return
}
startLogger.Log("msg", "started grpc listener", "address", grpcAddr)
grpcServer := grpc.NewServer()
pb.RegisterPlayersServer(grpcServer, grpcTransport)
startLogger.Log("transport", "grpc", "address", grpcAddr, "msg", "listening")
errs <- grpcServer.Serve(listener)
}()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errs <- fmt.Errorf("%s", <-c)
}()
logger.Log("terminated", <-errs)
}
func createLogger() log.Logger {
logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
return log.With(logger, "ts", log.DefaultTimestampUTC())
}
func createDatabase() (*sqlx.DB, error) {
db, err := sqlx.Connect("postgres", fmt.Sprintf("user=%s password=%s dbname=roster sslmode=disable",
os.Getenv("ROSTER_USER"),
os.Getenv("ROSTER_PASSWORD")))
if err != nil {
return nil, err
}
ddl, err := ioutil.ReadFile("create_table.sql")
if err != nil {
return nil, err
}
_, err = db.Exec(string(ddl))
return db, err
}
func createPlayersService(db *sqlx.DB, logger log.Logger) players.Service {
ps := players.NewService(db)
ps = players.NewLoggingService(log.With(logger, "tag", "players"), ps)
return ps
}