/
server.go
227 lines (202 loc) · 6.3 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
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
222
223
224
225
226
227
package server
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/felixge/httpsnoop"
"github.com/go-http-utils/etag"
"golang.org/x/sync/errgroup"
)
// TLSConfig holds TLS config options
type TLSConfig struct {
CertFile string `long:"cert" description:"CertFile for serving HTTPS instead HTTP" env:"CERT" `
KeyFile string `long:"key" description:"KeyFile for serving HTTPS instead HTTP" env:"KEY" `
NoCheckCertificate bool `long:"no-check" description:"disable tls certificate validation"`
}
// VersionResponseConfig
type VersionResponseConfig struct {
Prefix string `long:"prefix" default:"/js/version.js" description:"URL for version response"`
Format string `long:"format" default:"document.addEventListener('DOMContentLoaded', () => { appVersion.innerText = '%s'; });\n" description:"Format string for version response"`
CType string `long:"ctype" default:"text/javascript" description:"js code Content-Type header"`
}
// Config holds all config vars.
type Config struct {
Listen string `long:"listen" default:":8080" description:"Addr and port which server listens at"`
MaxHeaderBytes int `long:"maxheader" description:"MaxHeaderBytes"`
ReadTimeout time.Duration `long:"rto" default:"10s" description:"HTTP read timeout"`
WriteTimeout time.Duration `long:"wto" default:"60s" description:"HTTP write timeout"`
GracePeriod time.Duration `long:"grace" default:"10s" description:"Stop grace period"`
IPHeader string `long:"ip_header" env:"IP_HEADER" default:"X-Real-IP" description:"HTTP Request Header for remote IP"`
UserHeader string `long:"user_header" env:"USER_HEADER" default:"X-Username" description:"HTTP Request Header for username"`
TLS TLSConfig `group:"HTTPS Options" namespace:"tls" env-namespace:"TLS"`
Version VersionResponseConfig `group:"Version response Options" namespace:"vr"`
}
// Handler is a http midleware handler.
type Handler func(http.Handler) http.Handler
// Worker is a server goroutene worker.
type Worker func(ctx context.Context) error
// Service holds service attributes.
type Service struct {
config Config
listener net.Listener
mux *http.ServeMux
handlers []Handler
onShutdown *Worker
}
// New returns *Service.
func New(cfg Config) *Service {
return &Service{
config: cfg,
mux: http.NewServeMux(),
}
}
// WithListener sets service listener.
func (srv *Service) WithListener(listener net.Listener) *Service {
srv.listener = listener
return srv
}
// WithStatic sets static filesystem for serve via http.
func (srv *Service) WithStatic(fSystem fs.FS) *Service {
httpFileServer := http.FileServer(http.FS(fSystem))
srv.mux.Handle("/", httpFileServer)
return srv
}
// WithVersion sets hanler returning source code version as js.
func (srv *Service) WithVersion(version string) *Service {
srv.mux.HandleFunc(srv.config.Version.Prefix, func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", srv.config.Version.CType)
_, err := fmt.Fprintf(w, srv.config.Version.Format, version)
if err != nil {
slog.Error("Verion response", "err", err)
}
})
return srv
}
// Use adds handler for muxer.
func (srv *Service) Use(handler Handler) *Service {
srv.handlers = append(srv.handlers, handler)
return srv
}
// ServeMux returns service muxer.
func (srv Service) ServeMux() *http.ServeMux {
return srv.mux
}
// WithShutdown registers worker for call on shutdown.
func (srv *Service) WithShutdown(worker Worker) *Service {
srv.onShutdown = &worker
return srv
}
// Run runs the service.
func (srv Service) Run(ctxParent context.Context, workers ...Worker) error {
ctx, stop := signal.NotifyContext(ctxParent, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
defer stop()
cfg := srv.config
var mux http.Handler = srv.mux
for _, handler := range srv.handlers {
mux = handler(mux)
}
listener := srv.listener
if listener == nil {
var err error
slog.Debug("Start Listener", "addr", cfg.Listen)
if listener, err = net.Listen("tcp", cfg.Listen); err != nil {
return err
}
}
// Creating a normal HTTP server
server := &http.Server{
Handler: mux,
BaseContext: func(_ net.Listener) context.Context {
return ctx
},
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
MaxHeaderBytes: cfg.MaxHeaderBytes,
}
if cfg.TLS.NoCheckCertificate {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
// start servers
g, gCtx := errgroup.WithContext(ctx)
if srv.config.TLS.CertFile != "" {
slog.Debug("Start HTTPS service")
g.Go(func() error {
return server.ServeTLS(listener, srv.config.TLS.CertFile, srv.config.TLS.KeyFile)
})
} else {
slog.Debug("Start HTTP service")
g.Go(func() error {
return server.Serve(listener)
})
}
g.Go(func() error {
<-gCtx.Done()
slog.Debug("Shutdown")
stop()
timedCtx, cancel := context.WithTimeout(ctx, cfg.GracePeriod)
defer cancel()
var err error
if srv.onShutdown != nil {
w := *srv.onShutdown
err = w(timedCtx)
}
return errors.Join(err, server.Shutdown(timedCtx))
})
for _, worker := range workers {
w := worker
g.Go(func() error {
return w(gCtx)
})
}
if er := g.Wait(); er != nil && !errors.Is(er, http.ErrServerClosed) && !errors.Is(er, net.ErrClosed) {
return er
}
slog.Info("Exit")
return nil
}
// WithAccessLog calculates estimate and prints HTTP request log.
func (cfg Config) WithAccessLog(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(handler, w, r)
ip := r.Header.Get(cfg.IPHeader)
if ip == "" {
if colonPos := strings.Index(r.RemoteAddr, ":"); colonPos == -1 {
ip = r.RemoteAddr
} else {
ip = r.RemoteAddr[:colonPos]
}
}
user := r.Header.Get(cfg.UserHeader)
if user == "" {
user = "-"
}
fmt.Printf(`%s - %s [%s] "%s %s" %d %s %d %s%s`,
ip,
user,
time.Now().Format(time.DateTime),
r.Method,
r.URL,
m.Code,
m.Duration,
m.Written,
r.Header.Get("Referer"),
"\n",
)
})
}
// WithETag adds ETAG to response.
func (cfg Config) WithETag(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
etag.Handler(handler, false).ServeHTTP(w, r)
})
}