Repository navigation
Expand file tree
/
Copy pathhttpserver.go
More file actions
221 lines (194 loc) · 6.01 KB
/
Copy pathhttpserver.go
File metadata and controls
221 lines (194 loc) · 6.01 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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package httpserver
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/ing-bank/golibs/pkg/config"
"github.com/ing-bank/golibs/pkg/graceful"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
type Server struct {
*http.Server
shutdownTimeout time.Duration
errChan <-chan error
}
func New(opts ...Option) (*Server, error) {
cfg := DefaultConfig()
s, err := NewForConfig(cfg, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP server: %w", err)
}
return s, nil
}
func NewForConfig(cfg *Config, opts ...Option) (*Server, error) {
// apply default values to the configuration
cfg.ApplyDefaults()
// validate the configuration
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("validation failed: %w", err)
}
// configure the HTTP server with the provided configuration
s := &Server{
Server: &http.Server{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
ReadTimeout: cfg.ReadTimeout.Duration,
ReadHeaderTimeout: cfg.ReadHeaderTimeout.Duration,
WriteTimeout: cfg.WriteTimeout.Duration,
MaxHeaderBytes: cfg.MaxHeaderBytes,
},
shutdownTimeout: cfg.ShutdownTimeout.Duration,
errChan: make(chan error, 1),
}
// apply options to the server
if err := config.ApplyOpts(s, opts...); err != nil {
return nil, fmt.Errorf("failed to apply TLS option: %w", err)
}
// validate the server configuration
if err := s.Validate(); err != nil {
return nil, fmt.Errorf("validation failed: %w", err)
}
return s, nil
}
func DefaultServerConfig() *Server {
return &Server{
Server: &http.Server{
Addr: fmt.Sprintf("%s:%d", DefaultHost, DefaultPort),
ReadHeaderTimeout: time.Duration(DefaultReadHeaderTimeout),
ReadTimeout: time.Duration(DefaultReadTimeout),
WriteTimeout: time.Duration(DefaultWriteTimeout),
MaxHeaderBytes: DefaultMaxHeaderBytes,
},
shutdownTimeout: time.Duration(DefaultShutdownTimeout),
}
}
func (h *Server) ApplyDefaults() *Server {
if h.Server == nil {
h.Server = &http.Server{} //nolint // ReadHeaderTimeout is set later in ApplyDefaults
}
if h.Server.Addr == "" {
h.Server.Addr = fmt.Sprintf("%s:%d", DefaultHost, DefaultPort)
}
if h.Server.ReadTimeout <= 0 {
h.Server.ReadTimeout = time.Duration(DefaultReadTimeout)
}
if h.Server.ReadHeaderTimeout <= 0 {
h.Server.ReadHeaderTimeout = time.Duration(DefaultReadHeaderTimeout)
}
if h.Server.WriteTimeout <= 0 {
h.Server.WriteTimeout = time.Duration(DefaultWriteTimeout)
}
if h.Server.MaxHeaderBytes <= 0 {
h.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
}
if h.shutdownTimeout <= 0 {
h.shutdownTimeout = time.Duration(DefaultShutdownTimeout)
}
return h
}
func (h *Server) Validate() error {
if h.Server == nil {
return errors.New("httpServer cannot be nil")
}
if h.shutdownTimeout <= 0 {
return errors.New("shutdownTimeout must be a positive duration")
}
if h.Server.Addr == "" {
return errors.New("httpServer address cannot be empty")
}
if h.Server.ReadHeaderTimeout <= 0 {
return errors.New("httpServer ReadHeaderTimeout must be a positive duration")
}
if h.Server.WriteTimeout <= 0 {
return errors.New("httpServer WriteTimeout must be a positive duration")
}
if h.Server.MaxHeaderBytes <= 0 {
return errors.New("httpServer MaxHeaderBytes must be a positive integer")
}
if h.Server.TLSConfig != nil && h.Server.TLSConfig.MinVersion < tls.VersionTLS12 {
return errors.New("httpServer TLSConfig must have a minimum version of TLS 1.2")
}
return nil
}
func (h *Server) RegisterRoutes(routes ...http.Handler) {
for _, route := range routes {
h.Server.Handler.(*gin.Engine).Use(gin.WrapH(route))
}
}
func Run(ctx context.Context, r http.Handler) error {
// Create a new HTTP server
s := defaultServer().withHandler(r)
// Run the server with the provided context
return run(ctx, s.Server, s.shutdownTimeout)
}
func RunTLS(ctx context.Context, r http.Handler, tlsConfig *tls.Config) error {
// Create a new HTTP server
s, err := New(WithHandler(r), WithTLS(tlsConfig))
if err != nil {
return err
}
return run(ctx, s.Server, s.shutdownTimeout)
}
func (h *Server) Run(ctx context.Context) error {
return run(ctx, h.Server, h.shutdownTimeout)
}
func (h *Server) RunBackground(ctx context.Context) <-chan error {
h.errChan = graceful.RunBackground(ctx, func(ctx context.Context) error {
return run(ctx, h.Server, h.shutdownTimeout)
})
return h.errChan
}
func (h *Server) Wait() error {
if h.errChan == nil {
return nil
}
return <-h.errChan
}
func run(ctx context.Context, httpServer *http.Server, shutdownTimeout time.Duration) error {
if httpServer.Handler == nil {
return errors.New("httpServer handler cannot be nil")
}
return graceful.Run(ctx, func(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
if httpServer.TLSConfig != nil {
log.WithContext(ctx).Infof("starting HTTPS server on %s...", httpServer.Addr)
return httpServer.ListenAndServeTLS("", "")
}
log.WithContext(ctx).Infof("starting HTTP server on %s...", httpServer.Addr)
return httpServer.ListenAndServe()
})
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
// Wait for context cancellation and gracefully shut down the server
g.Go(func() error {
<-ctx.Done()
log.WithContext(ctx).Info("shutting down server...")
return httpServer.Shutdown(shutdownCtx)
})
if err := g.Wait(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("server error: %w", err)
}
log.WithContext(ctx).Info("server shutdown complete")
return nil
}, graceful.NewRunOptions(shutdownTimeout))
}
func defaultServer() *Server {
server, err := New()
if err != nil {
log.Fatalf("Failed to create HTTP server: %v", err)
}
return server
}
func (h *Server) withHandler(handler http.Handler) *Server {
if handler == nil {
log.Warn("Handler is nil, using default handler")
handler = http.DefaultServeMux
}
h.Server.Handler = handler
return h
}