-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
94 lines (74 loc) · 1.98 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
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/sjain93/userservice/api/user"
"github.com/sjain93/userservice/config"
"github.com/sjain93/userservice/migrations"
"github.com/sjain93/userservice/routes"
)
func main() {
var (
userRepository user.UserRepoManager
err error
)
noDB := flag.Bool("noDB", false, "Bool if the server should init in memory store")
flag.Parse()
if *noDB {
inMemDB := config.GetInMemoryStore()
userRepository, err = user.NewUserRepository(nil, inMemDB)
if err != nil {
log.Fatalf("Error initializing in memory datastore: %v", err.Error())
}
} else {
err = config.LoadEnvVars()
if err != nil {
log.Fatalf("Error loading .env file")
}
config.ConnectDatabase()
migrations.AutoMigrate(config.DB)
userRepository, err = user.NewUserRepository(config.DB, nil)
if err != nil {
log.Fatalf("Error initializing postgres datastore: %v", err.Error())
}
}
userService := user.NewUserService(userRepository)
e := echo.New()
e.Use(
middleware.Logger(),
middleware.Recover(),
middleware.RequestID(),
)
routes.SetupAPIRoutes(e, userService)
/*
The code below implements a graceful shutdown by starting the server
via a goroutine that blocks until a kill command is posted
*/
shutdownCtx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
go func() {
if err := e.Start(":8080"); err != nil && err != http.ErrServerClosed {
e.Logger.Fatal("shutting down the server")
}
}()
<-shutdownCtx.Done() // block here until ctrl+c
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}
/*
An optional route can be added to trigger a graceful shutdown over HTTP:
e.POST("/quit", func(c echo.Context) error {
cancel()
return c.String(http.StatusOK, "OK")
})
*/