-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
94 lines (74 loc) · 2.05 KB
/
main.go
File metadata and controls
94 lines (74 loc) · 2.05 KB
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"
"errors"
"go-api-template/configuration"
"go-api-template/controller"
"go-api-template/middleware"
"go-api-template/model"
"go-api-template/pkg/logger"
"go-api-template/repository"
"go-api-template/service"
"log"
"net/http"
"os"
"os/signal"
"time"
_ "gorm.io/driver/postgres"
)
// @title Go API
// @version 1.0
// @description GO API documentation
// @securityDefinitions.basic BasicAuth.
func main() {
// Initialize the logger
logger.InitLogger()
// Load the configuration
cfg, err := configuration.Load()
if err != nil {
logger.Errorf("configuration loading failed: %v", err)
}
// Initialize validation
if err := model.InitValidation(); err != nil {
log.Fatalf("failed to initialize validation: %v", err)
}
// Initialize the database connection
dbConnection := repository.NewConnection(cfg)
defer dbConnection.Close()
// Initialize repositories
repository := repository.NewRepositories(dbConnection)
// Initialize services
services := service.NewServices(cfg, repository)
// Initialize the controllers
controllers := controller.NewControllers(services)
// Initialize router
router, err := middleware.NewRouter(cfg, controllers)
if err != nil {
logger.Errorf("initializing router failed: %v", err)
}
srv := &http.Server{
Addr: ":" + cfg.AppPort,
Handler: router,
// set timeout due CWE-400 - Potential Slowloris Attack
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
logger.Infof("Listening server on port %s...", cfg.AppPort)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatalf("Server failed to start: %v", err)
}
}()
gracefulShutdown(srv)
}
func gracefulShutdown(srv *http.Server) {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
logger.Infof("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.Fatalf("Server forced to shutdown: %v", err)
}
logger.Infof("Server exiting")
}