-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.go
197 lines (181 loc) · 5.56 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
// Copyright 2023 sigma
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"crypto/sha256"
"hash"
"hash/crc32"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo-contrib/pprof"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/rs/zerolog/log"
"github.com/go-sigma/sigma/pkg/builder"
"github.com/go-sigma/sigma/pkg/configs"
"github.com/go-sigma/sigma/pkg/consts"
"github.com/go-sigma/sigma/pkg/graceful"
"github.com/go-sigma/sigma/pkg/handlers"
"github.com/go-sigma/sigma/pkg/inits"
"github.com/go-sigma/sigma/pkg/middlewares"
"github.com/go-sigma/sigma/pkg/modules/workq"
"github.com/go-sigma/sigma/pkg/storage"
"github.com/go-sigma/sigma/pkg/types/enums"
"github.com/go-sigma/sigma/pkg/utils/ptr"
"github.com/go-sigma/sigma/pkg/utils/serializer"
"github.com/go-sigma/sigma/web"
)
// ServerConfig ...
type ServerConfig struct {
WithoutDistribution bool
WithoutWorker bool
WithoutWeb bool
}
// Serve starts the server
func Serve(serverConfig ServerConfig) error {
e := echo.New()
e.HideBanner = true
e.HidePort = true
e.Use(echo.MiddlewareFunc(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
log.Debug().
Str("method", c.Request().Method).
Str("path", c.Request().URL.Path).
Str("query", c.Request().URL.RawQuery).
// Interface("req-header", c.Request().Header).
// Interface("resp-header", c.Response().Header()).
// Int("status", c.Response().Status).
Msg("Request debugger")
reqPath := c.Request().URL.Path
if strings.HasPrefix(reqPath, "/assets/") {
if strings.HasSuffix(c.Request().URL.Path, ".js") ||
strings.HasSuffix(c.Request().URL.Path, ".map") ||
strings.HasSuffix(c.Request().URL.Path, ".css") ||
strings.HasSuffix(c.Request().URL.Path, ".svg") ||
strings.HasSuffix(c.Request().URL.Path, ".png") ||
strings.HasSuffix(c.Request().URL.Path, ".ttf") ||
strings.HasSuffix(c.Request().URL.Path, ".json") ||
strings.HasSuffix(c.Request().URL.Path, ".yaml") {
c.Response().Header().Add("Cache-Control", "max-age=3600")
}
}
n := next(c)
return n
}
}))
config := ptr.To(configs.GetConfiguration())
e.Use(middleware.CORS())
e.Use(middlewares.WithEtagConfig(middlewares.EtagConfig{
Skipper: func(c echo.Context) bool {
reqPath := c.Request().URL.Path
if strings.HasPrefix(reqPath, "/api/v1/") {
return true
}
if strings.HasPrefix(reqPath, "/v2/") {
return true
}
return false
},
Weak: true,
HashFn: func(config middlewares.EtagConfig) hash.Hash {
if config.Weak {
const crcPol = 0xD5828281
crc32qTable := crc32.MakeTable(crcPol)
return crc32.New(crc32qTable)
}
return sha256.New()
},
}))
e.Use(echoprometheus.NewMiddleware(consts.AppName))
e.GET("/metrics", echoprometheus.NewHandler())
e.Use(middlewares.Healthz())
if config.Log.Level == enums.LogLevelDebug || config.Log.Level == enums.LogLevelTrace {
pprof.Register(e, consts.PprofPath)
}
e.Use(middlewares.RedirectRepository(config))
e.JSONSerializer = new(serializer.DefaultJSONSerializer)
if !serverConfig.WithoutDistribution {
handlers.InitializeDistribution(e)
}
if !serverConfig.WithoutWorker {
err := builder.Initialize(config)
if err != nil {
return err
}
err = workq.Initialize(config)
if err != nil {
return err
}
}
if !serverConfig.WithoutWeb {
web.RegisterHandlers(e)
}
err := handlers.Initialize(e)
if err != nil {
return err
}
err = storage.Initialize(config)
if err != nil {
return err
}
go func() {
log.Info().Str("addr", consts.ServerPort).Msg("Server listening")
if config.HTTP.TLS.Enabled {
crtBytes, err := os.ReadFile(config.HTTP.TLS.Certificate)
if err != nil {
log.Fatal().Err(err).Str("certificate", config.HTTP.TLS.Certificate).Msgf("Read certificate failed")
return
}
keyBytes, err := os.ReadFile(config.HTTP.TLS.Key)
if err != nil {
log.Fatal().Err(err).Str("key", config.HTTP.TLS.Key).Msgf("Read key failed")
return
}
err = e.StartTLS(consts.ServerPort, crtBytes, keyBytes)
if err != http.ErrServerClosed {
log.Fatal().Err(err).Msg("Listening on interface failed")
}
} else {
err = e.Start(consts.ServerPort)
if err != http.ErrServerClosed {
log.Fatal().Err(err).Msg("Listening on interface failed")
}
}
}()
if !serverConfig.WithoutDistribution {
<-time.After(time.Second * 3)
err = inits.AfterInitialize(config)
if err != nil {
log.Error().Err(err).Msg("init something after server initialized")
}
}
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
// Use a buffered channel to avoid missing signals as recommended for signal.Notify
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = e.Shutdown(ctx)
if err != nil {
log.Error().Err(err).Msg("Server shutdown failed")
}
graceful.Shutdown()
return nil
}