-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgss.go
301 lines (262 loc) · 7.17 KB
/
gss.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/felixge/httpsnoop"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v2"
)
func main() {
setUpLogger()
var metrics *metrics
cfg := newConfig().withYAML()
if cfg.MetricsEnabled {
metrics = registerMetrics()
internalServer := newInternalServer(cfg, metrics)
go func() {
err := internalServer.run()
if err != nil {
log.Fatal().Msgf("Error starting internal server: %v", err)
}
}()
}
err := newFileServer(cfg, metrics).init().run()
if err != nil {
log.Fatal().Msgf("Error starting file server: %v", err)
}
}
func setUpLogger() {
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
zerolog.TimeFieldFormat = time.RFC3339Nano
log.Logger = log.With().Timestamp().Caller().Str("app", "GSS").Logger()
}
type config struct {
FilesPort int `yaml:"filesPort,omitempty"`
MetricsPort int `yaml:"metricsPort,omitempty"`
MetricsEnabled bool `yaml:"metrics,omitempty"`
}
func newConfig() *config {
return &config{
// Default values
FilesPort: 8080,
MetricsPort: 8081,
MetricsEnabled: false,
}
}
func (c *config) withYAML() *config {
file := "gss.yaml"
_, err := os.Stat(file)
if os.IsNotExist(err) {
// If no file is found we assume config via YAML is not used
return c
}
data, err := os.ReadFile(file)
if err != nil {
log.Fatal().Msgf("Error reading config file: %v", err)
}
err = yaml.Unmarshal([]byte(data), &c)
if err != nil {
log.Fatal().Msgf("Error unmarshalling file data: %v", err)
}
return c
}
type fileServer struct {
Config *config
Metrics *metrics
Server *http.Server
}
func newFileServer(cfg *config, metrics *metrics) *fileServer {
return &fileServer{
Config: cfg,
Metrics: metrics,
Server: &http.Server{
Addr: ":" + strconv.Itoa(cfg.FilesPort),
WriteTimeout: 10 * time.Second,
},
}
}
func (f *fileServer) init() *fileServer {
if f.Config.MetricsEnabled {
f.Server.Handler = metricsMiddleware(f.Metrics)(f.setHeaders((f.serveSPA())))
} else {
f.Server.Handler = f.setHeaders((f.serveSPA()))
}
return f
}
func (f *fileServer) run() error {
return f.Server.ListenAndServe()
}
func (f *fileServer) setHeaders(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Vary", "Accept-Encoding")
h.ServeHTTP(w, r)
}
}
func (f *fileServer) serveSPA() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
dir := "dist"
requestedFile := filepath.Join(dir, filepath.Clean(r.URL.Path))
// Send the index if the root path is requested.
if filepath.Clean(r.URL.Path) == "/" {
requestedFile = filepath.Join(dir, "index.html")
}
// Send a 404 if a file with extension is not found, and the index if it has no extension,
// as it will likely be a SPA route.
_, err := os.Stat(requestedFile)
if os.IsNotExist(err) {
if filepath.Ext(requestedFile) != "" {
w.WriteHeader(http.StatusNotFound)
return
}
requestedFile = filepath.Join(dir, "index.html")
}
serveFile := func(mimeType string) {
availableFiles := getFiles(dir)
acceptedEncodings := r.Header.Get("Accept-Encoding")
brotli := "br"
brotliExt := ".br"
gzip := "gzip"
gzipExt := ".gz"
serveCompressed := func(encoding, extension string) {
w.Header().Set("Content-Encoding", encoding)
w.Header().Set("Content-Type", mimeType)
http.ServeFile(w, r, requestedFile+extension)
}
if strings.Contains(acceptedEncodings, brotli) {
for _, f := range availableFiles {
if f == requestedFile+brotliExt {
serveCompressed(brotli, brotliExt)
return
}
}
}
if strings.Contains(acceptedEncodings, gzip) {
for _, f := range availableFiles {
if f == requestedFile+gzipExt {
serveCompressed(gzip, gzipExt)
return
}
}
}
// If the request does not accept compressed files, or the directory does not contain compressed files,
// serve the file as is.
http.ServeFile(w, r, requestedFile)
}
switch filepath.Ext(requestedFile) {
case ".html":
w.Header().Set("Cache-Control", "no-cache")
serveFile("text/html")
case ".css":
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
serveFile("text/css")
case ".js":
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
serveFile("application/javascript")
case ".svg":
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
serveFile("image/svg+xml")
default:
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
http.ServeFile(w, r, requestedFile)
}
}
}
func getFiles(dir string) []string {
files := []string{}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
files = append(files, path)
return nil
})
if err != nil {
log.Error().Msgf("Error getting files to serve: %v", err)
}
return files
}
type internalServer struct {
Server *http.Server
}
func newInternalServer(cfg *config, metrics *metrics) *internalServer {
http.HandleFunc("/metrics", metrics.Default().ServeHTTP)
return &internalServer{
Server: &http.Server{
Addr: ":" + strconv.Itoa(cfg.MetricsPort),
},
}
}
func (i *internalServer) run() error {
return i.Server.ListenAndServe()
}
type metrics struct {
requestsReceived *prometheus.CounterVec
requestDuration *prometheus.HistogramVec
bytesWritten prometheus.Counter
}
func registerMetrics() *metrics {
const labelCode = "code"
reqReceived := promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "http",
Name: "requests_total",
Help: "Total number of requests received.",
},
[]string{labelCode},
)
reqDuration := promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "http",
Name: "request_duration_seconds",
Help: "Duration of a request in seconds.",
},
[]string{labelCode},
)
bytesWritten := promauto.NewCounter(
prometheus.CounterOpts{
Namespace: "http",
Name: "bytes_written_total",
Help: "Total number of bytes written.",
},
)
return &metrics{
requestsReceived: reqReceived,
requestDuration: reqDuration,
bytesWritten: bytesWritten,
}
}
func (m *metrics) Default() http.Handler {
return promhttp.Handler()
}
func (m *metrics) IncRequests(code int) {
m.requestsReceived.WithLabelValues(strconv.Itoa(code)).Inc()
}
func (m *metrics) ObsDuration(code int, duration float64) {
m.requestDuration.WithLabelValues(strconv.Itoa(code)).Observe(duration)
}
func (m *metrics) AddBytes(bytes float64) {
m.bytesWritten.Add(bytes)
}
func metricsMiddleware(metrics *metrics) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
snoop := httpsnoop.CaptureMetrics(h, w, r)
metrics.IncRequests(snoop.Code)
metrics.ObsDuration(snoop.Code, snoop.Duration.Seconds())
metrics.AddBytes(float64(snoop.Written))
})
}
}