-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (75 loc) · 2.11 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
package main
import (
"bash06/tipitipi-backend/core"
"bash06/tipitipi-backend/flags"
"bash06/tipitipi-backend/srv"
"context"
"flag"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func main() {
flag.Parse()
log, err := core.InitLogger()
if err != nil {
panic("Failed to initialize logger: " + err.Error())
}
db, err := core.InitDb()
if err != nil {
log.Fatal("Failed to initialize database:", zap.Error(err))
}
if !*flags.Dev {
gin.SetMode(gin.ReleaseMode)
}
server, err := srv.New(&srv.ServerConfig{
CorsConfig: &cors.Config{
AllowMethods: []string{"HEAD", "POST", "DELETE", "PATCH", "GET"},
AllowHeaders: []string{"Content-Type", "Authorization"},
AllowOrigins: []string{"http://localhost*", "https://tipitipi.pl"},
AllowCredentials: true,
AllowFiles: false,
AllowWebSockets: false,
AllowBrowserExtensions: false,
AllowWildcard: true,
},
HttpConfig: &http.Server{},
Logger: log,
Db: db,
Port: flags.Port,
})
if err != nil {
log.Fatal("Failed to initialize server", zap.Error(err))
}
server.InitHandler()
go func() {
if !*flags.Secure {
if err := server.Http.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal("Failed to start server", zap.Error(err))
}
} else {
if err := server.Http.ListenAndServeTLS(*flags.CertFilePath, *flags.KeyFilePath); err != nil && err != http.ErrServerClosed {
log.Fatal("Failed to start secure server", zap.Error(err))
}
}
}()
log.Info("Server started. Listening to requests...")
// Keeps the server from shutting itself down
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
log.Info("Gracefully shutting down backend server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Http.Shutdown(ctx); err != nil {
log.Fatal("Server shutdown:", zap.Error(err))
}
if <-ctx.Done(); true {
log.Error("Timed out after 5 seconds")
}
log.Info("Server exiting")
}