-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgin.go
More file actions
90 lines (73 loc) · 2.16 KB
/
gin.go
File metadata and controls
90 lines (73 loc) · 2.16 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
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Stogas/feedback-api/internal/config"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func startAPI(conf config.APIConfig, globalMiddlewares []gin.HandlerFunc, dbMiddleware gin.HandlerFunc) {
if conf.Debug {
gin.SetMode(gin.DebugMode)
}
r := gin.New()
r.Use(gin.Recovery())
corsConfig := cors.DefaultConfig()
corsConfig.AllowOrigins = conf.CorsOrigins
corsConfig.AllowHeaders = append(corsConfig.AllowHeaders, "X-Feedback-Submit-Token")
corsConfig.MaxAge = 1 * time.Hour
corsConfig.AllowWildcard = true
r.Use(cors.New(corsConfig))
for _, m := range globalMiddlewares {
// slog.Debug("Gin: Adding middleware")
r.Use(m)
}
r.GET("/ping", ping)
r.GET("/issues", dbMiddleware, GetIssuesEndpoint)
rSubmit := r.Group("/submit")
rSubmit.Use(
submitTokenMiddleware(conf.SubmitToken),
dbMiddleware,
reportMiddleware,
)
{
rSubmit.POST("/report", submitReportEndpoint)
rSubmit.PATCH("/report", updateReportEndpoint)
}
slog.Info("Starting API", "host", conf.Host, "port", conf.Port)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%v", conf.Host, conf.Port),
Handler: r.Handler(),
}
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("API listener failed", "error", err)
}
}()
apiGracefulShutdown(srv)
}
func apiGracefulShutdown(srv *http.Server) {
// Graceful shutdown
// Wait for interrupt signal to gracefully shutdown the server with timeout
timeout := 5 * time.Second
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
slog.Info("Shutting down API listener ...", "timeout", timeout)
// timeout of 5 seconds
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
slog.Error("Error while shutting down API listener gracefully. Initiating force shutdown...", "error", err, "timeout", timeout)
} else {
slog.Info("API listener exited successfully")
}
}