-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (90 loc) · 2.5 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
104
105
106
package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/oschwald/geoip2-golang"
"github.com/sirupsen/logrus"
)
func main() {
// create new logger
log := logrus.New()
// Create a config from env variables with a prefix
cfg, err := newCfg("")
if err != nil {
log.Fatalf("main: Error loading config: %s", err.Error())
}
// Configure logger
level, err := logrus.ParseLevel(cfg.Log.Level)
if err != nil {
level = logrus.InfoLevel
log.Error(err.Error())
}
if cfg.Log.Debug {
level = logrus.DebugLevel
}
log.SetLevel(level)
// Adjust logging format
log.SetFormatter(&logrus.JSONFormatter{})
if cfg.Log.Dev {
log.SetFormatter(&logrus.TextFormatter{})
}
// Open database file
db, err := geoip2.Open(cfg.Database.Path)
if err != nil {
log.Fatal(err)
}
// create middlewares for our api server
// by createing a list of middlewares to enable on http server
mw := []func(http.Handler) http.Handler{
render.SetContentType(render.ContentTypeJSON),
loggerMiddleware(log),
middleware.DefaultCompress,
middleware.RedirectSlashes,
middleware.Recoverer,
}
// create the http.Server
api := http.Server{
Addr: cfg.Web.Host + ":" + cfg.Web.Port,
Handler: newServer(log, db, mw...),
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Listening channel for errors
serverErrors := make(chan error, 1)
// Start the service listening for requests.
go func() {
log.Debugf("Starting api Listening %s:%s", cfg.Web.Host, cfg.Web.Port)
serverErrors <- api.ListenAndServe()
}()
// ========================================
// Shutdown
//
// Listen for os signals
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
// ========================================
// Stop API Service
// Blocking main and waiting for shutdown.
select {
case err := <-serverErrors:
log.Fatalf("Error starting server: %v", err)
case <-osSignals:
log.Info("Start shutdown...")
// Create context for Shutdown call.
ctx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
defer cancel()
// Asking listener to shutdown and load shed.
if err := api.Shutdown(ctx); err != nil {
log.Infof("Graceful shutdown did not complete in %v: %v", cfg.Web.ShutdownTimeout, err)
if err := api.Close(); err != nil {
log.Fatalf("Could not stop http server: %v", err)
}
}
}
}