-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
145 lines (122 loc) · 3.71 KB
/
server.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package http
import (
"context"
"errors"
"net/http"
"regexp"
"sync"
"time"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
healthcheck "github.com/tavsec/gin-healthcheck"
"github.com/tavsec/gin-healthcheck/checks"
"github.com/tavsec/gin-healthcheck/config"
timeout "github.com/vearne/gin-timeout"
"github.com/xBlaz3kx/DevX/observability"
"github.com/xBlaz3kx/DevX/tls"
"go.uber.org/zap"
)
var once sync.Once
// Http configuration for the API with TLS settings
type Configuration struct {
// Address is the address of the HTTP server
Address string `yaml:"address" json:"address" mapstructure:"address"`
CORS *CORS `yaml:"cors" json:"cors" mapstructure:"cors"`
// TLS is the TLS configuration for the HTTP server
TLS tls.TLS `mapstructure:"tls" yaml:"tls" json:"tls"`
}
type Server struct {
config Configuration
router *gin.Engine
server *http.Server
obs observability.Observability
}
func NewServer(config Configuration, obs observability.Observability, optionFuncs ...func(*Options)) *Server {
options := newOptions()
router := gin.New()
logger := obs.Log().Logger
// Apply options
for _, optionFunc := range optionFuncs {
optionFunc(options)
}
once.Do(func() {
gin.DebugPrintFunc = func(format string, values ...interface{}) {
// Remove newlines and tabs from the format string
regex := regexp.MustCompile(`[\n\t]`)
logger.Sugar().Debugf(regex.ReplaceAllString(format, ""), values...)
}
})
obs.SetupGinMiddleware(router)
router.NoRoute(func(context *gin.Context) {
context.JSON(http.StatusNotFound, ErrorPayload{
Error: "Not Found",
Description: "The requested resource was not found",
})
})
router.NoMethod(func(context *gin.Context) {
context.JSON(http.StatusMethodNotAllowed, ErrorPayload{
Error: "Not Allowed",
Description: "Method not allowed",
})
})
router.Use(
ginzap.RecoveryWithZap(logger, true),
ginzap.Ginzap(logger, time.RFC3339, true),
timeout.Timeout(
timeout.WithTimeout(options.timeout),
timeout.WithErrorHttpCode(http.StatusServiceUnavailable),
timeout.WithDefaultMsg(EmptyResponse{}),
),
errorHandler,
)
return &Server{
config: config,
router: router,
}
}
func (s *Server) Router() *gin.Engine {
return s.router
}
// Run starts the HTTP server with the given healthchecks.
func (s *Server) Run(checks ...checks.Check) {
// swagger:route GET /healthz healthCheck internal livelinessCheck
// Perform healthcheck on the service.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
// Responses:
// default: emptyResponse
// 200: emptyResponse
// 503: errorResponse
// Add a healthcheck endpoint
err := healthcheck.New(s.router, config.DefaultConfig(), checks)
if err != nil {
s.obs.Log().With(zap.Error(err)).Panic("Cannot initialize healthcheck endpoint")
return
}
s.server = &http.Server{Addr: s.config.Address, Handler: s.router}
go func() {
if s.config.TLS.IsEnabled {
if err := s.server.ListenAndServeTLS(s.config.TLS.CertificatePath, s.config.TLS.PrivateKeyPath); err != nil && !errors.Is(err, http.ErrServerClosed) {
s.obs.Log().Panic("HTTP server failed to start", zap.Error(err))
}
}
if err := s.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
s.obs.Log().Panic("HTTP server failed to start", zap.Error(err))
}
}()
}
// Shutdown stops the HTTP server gracefully
func (s *Server) Shutdown() {
s.obs.Log().Info("Shutting down the HTTP server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.server.Shutdown(ctx); err != nil {
s.obs.Log().Error("HTTP server shutdown failed", zap.Error(err))
}
}