-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (87 loc) · 2.55 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 (
"context"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/Aloe-Corporation/logs"
"github.com/FloRichardAloeCorp/gateway/internal/configuration"
"github.com/FloRichardAloeCorp/gateway/internal/proxy"
"github.com/FloRichardAloeCorp/gateway/internal/service"
"github.com/gin-contrib/cors"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
var log = logs.Get()
const (
PREFIX_ENV = "GATEWAY"
ENV_CONFIG = PREFIX_ENV + "_CONFIG"
DEFAULT_PATH_CONFIG = "/config/"
)
func main() {
log.Info("loading configuration...")
configFilePath, present := os.LookupEnv(ENV_CONFIG)
if !present {
configFilePath = DEFAULT_PATH_CONFIG
}
config, err := configuration.LoadConf(configFilePath, "GATEWAY")
if err != nil {
panic(err)
}
log.Info("configuration loaded")
log.Info("proxy package initialization...")
proxy.Init()
log.Info("proxy package initialized")
router := gin.New()
router.Use(ginzap.RecoveryWithZap(log, true))
router.Use(ginzap.Ginzap(log, time.RFC3339, true))
router.Use(cors.New(cors.Config{
AllowOrigins: config.Server.Cors.AllowOrigins,
AllowMethods: config.Server.Cors.AllowMethods,
AllowHeaders: config.Server.Cors.AllowHeaders,
ExposeHeaders: config.Server.Cors.ExposeHeaders,
AllowCredentials: config.Server.Cors.AllowCredentials,
MaxAge: config.Server.Cors.MaxAge,
}))
log.Info("Creating endpoints...")
for _, serviceConf := range config.Services {
service, err := service.New(serviceConf)
if err != nil {
panic(err)
}
service.AttachEndpoints(router)
}
log.Info("endpoints created")
addrGin := ":" + strconv.Itoa(config.Server.Port)
srv := &http.Server{
ReadHeaderTimeout: time.Millisecond,
Addr: addrGin,
Handler: router,
}
go RunGin(addrGin, router)
WaitSignalShutdown(srv)
}
func RunGin(addr string, engine *gin.Engine) {
log.Info("REST API listening on : "+addr,
zap.String("package", "main"))
log.Error(engine.Run(addr).Error(),
zap.String("package", "main"))
}
func WaitSignalShutdown(srv *http.Server) {
// Wait for interrupt signal to gracefully shutdown the server
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Info("Shutdown Server ...")
// Time to wait before close forcing
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Error("Server Shutdown: ", zap.Error(err))
}
log.Info("Server exiting")
}