-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (61 loc) · 1.78 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
package main
import (
"context"
"database/sql"
log "github.com/sirupsen/logrus"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
const (
dbDriver = "postgres"
dbSource = "postgresql://root:secret@localhost:5555/simple_wallet?sslmode=disable"
serverAddress = "localhost:8080"
)
func main() {
log.SetFormatter(&log.TextFormatter{})
log.Println("starting wallet service")
db := newStore()
defer db.Close()
r := createRouter()
r = initRoutes(db, r)
server := &http.Server{Addr: serverAddress, Handler: r}
serverCtx, serverStopCtx := context.WithCancel(context.Background())
// Listen for syscall signals for process to interrupt/quit
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-sig
// Shutdown signal with grace period of 30 seconds
shutdownCtx, _ := context.WithTimeout(serverCtx, 30*time.Second)
go func() {
<-shutdownCtx.Done()
if shutdownCtx.Err() == context.DeadlineExceeded {
log.Fatal("graceful shutdown timed out.. forcing exit.")
}
}()
// Trigger graceful shutdown
err := server.Shutdown(shutdownCtx)
if err != nil {
log.Fatal("", err)
}
serverStopCtx()
}()
// Run the server
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal("failed to start server", err)
os.Exit(1)
}
// Wait for server context to be stopped
<-serverCtx.Done()
}
func newStore() *sql.DB {
conn, err := sql.Open(dbDriver, dbSource)
if err != nil {
log.Fatal("cannot connect to db", err)
}
return conn
}