-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
310 lines (265 loc) · 6.86 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
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
302
303
304
305
306
307
308
309
310
//go:generate ifacemaker -f $GOFILE -s Server -i ServerRepo -p server -o repository.go
//go:generate mockgen -source=repository.go -package=${GOPACKAGE} -destination=${GOPACKAGE}_mock.go
package server
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// Kind represents the type of router group
type Kind int
const (
ROOT Kind = iota
V1
V2
V3
DEV
API
DOCS
)
func (k Kind) String() string {
return [...]string{
"root",
"v1",
"v2",
"v3",
"dev",
"api",
"docs",
}[k]
}
// RegisterRouter defines a single router with a path and methods
type RegisterRouter struct {
Path string
Methods map[string]HandlerFunc
}
// RegisterRouters holds multiple routers with a fixed path prefix
type RegisterRouters struct {
PathFixed string
Routers []RegisterRouter
}
// NewRouters creates a new instance of RegisterRouters
func NewRouters() *RegisterRouters {
return &RegisterRouters{}
}
// AddRouter adds a new router to the list
func (r *RegisterRouters) AddRouter(path string, methods map[string]HandlerFunc) {
r.Routers = append(r.Routers, RegisterRouter{
Path: path,
Methods: methods,
})
}
// AddRouterFx adds a new router with a fixed path prefix
func (r *RegisterRouters) AddRouterFx(params string, methods map[string]HandlerFunc) {
path := strings.TrimSpace(params)
if len(path) > 0 {
path = r.PathFixed + path
} else {
path = r.PathFixed
}
r.Routers = append(r.Routers, RegisterRouter{
Path: path,
Methods: methods,
})
}
// GetAllRouters returns all registered routers
func (r *RegisterRouters) GetAllRouters() []RegisterRouter {
return r.Routers
}
// GetRouters returns routers matching the specified path
func (r *RegisterRouters) GetRouters(path string) []RegisterRouter {
var routers []RegisterRouter
for _, router := range r.Routers {
if router.Path == path {
routers = append(routers, router)
}
}
return routers
}
// GetRoutersFx returns routers containing the fixed path prefix
func (r *RegisterRouters) GetRoutersFx() []RegisterRouter {
var routers []RegisterRouter
for _, router := range r.Routers {
if strings.Contains(router.Path, r.PathFixed) {
routers = append(routers, router)
}
}
return routers
}
// SetPathFixed sets the fixed path prefix
func (r *RegisterRouters) SetPathFixed(path string) {
r.PathFixed = path
}
type Methods map[string]HandlerFunc
type HandlerFunc = echo.HandlerFunc
type MiddlewareFunc = echo.MiddlewareFunc
type Context = echo.Context
type Route = echo.Route
// Server represents the HTTP server
type Server struct {
port string
host string
echo *echo.Echo
params *ServerParams
}
// NewServer creates a new server instance with the given options
func NewServer(opts ...Options) (*Server, error) {
params, err := newServerParams(opts...)
if err != nil {
return nil, err
}
e := echo.New()
e.HideBanner = true
return &Server{
echo: e,
port: params.GetPort(),
host: params.GetHost(),
params: params,
}, nil
}
func (s *Server) MiddlewareLogger() MiddlewareFunc {
return middleware.Logger()
}
func (s *Server) MiddlewareRecover() MiddlewareFunc {
return middleware.Recover()
}
func (s *Server) MiddlewareCors() MiddlewareFunc {
return middleware.CORS()
}
func (s *Server) Use(middleware MiddlewareFunc) {
s.echo.Use(middleware)
}
func (s *Server) Uses(middlewares ...MiddlewareFunc) {
s.echo.Use(middlewares...)
}
// NewContext creates a new Echo context
func (s *Server) NewContext(req *http.Request, w http.ResponseWriter) Context {
return s.echo.NewContext(req, w)
}
// RegisterRouters registers multiple routers with the specified group and middlewares
func (s *Server) RegisterRouters(group Kind, routers *RegisterRouters, middlewares ...MiddlewareFunc) error {
var grp any
switch group {
case ROOT:
grp = s.echo
case V1, V2, V3, DEV, API, DOCS:
grp = s.echo.Group(group.String())
default:
return fmt.Errorf("invalid group type")
}
return s.registerRouters(grp, routers, middlewares...)
}
// registerRouters registers routers to the given Echo group or instance
func (s *Server) registerRouters(engine any, routers *RegisterRouters, middlewares ...MiddlewareFunc) error {
for _, middleware := range middlewares {
switch e := engine.(type) {
case *echo.Group:
e.Use(middleware)
case *echo.Echo:
e.Use(middleware)
}
}
for _, methods := range routers.GetAllRouters() {
for method, handler := range methods.Methods {
if err := s.registerMethod(engine, method, methods.Path, handler); err != nil {
return err
}
}
}
return nil
}
// registerMethod registers a single method to the Echo instance
func (s *Server) registerMethod(engine any, method, path string, handler echo.HandlerFunc) error {
switch e := engine.(type) {
case *echo.Group:
switch method {
case http.MethodGet:
e.GET(path, handler)
case http.MethodPost:
e.POST(path, handler)
case http.MethodPut:
e.PUT(path, handler)
case http.MethodDelete:
e.DELETE(path, handler)
case http.MethodPatch:
e.PATCH(path, handler)
case http.MethodHead:
e.HEAD(path, handler)
case http.MethodConnect:
e.CONNECT(path, handler)
case http.MethodOptions:
e.OPTIONS(path, handler)
case http.MethodTrace:
e.TRACE(path, handler)
default:
return fmt.Errorf("unsupported method: %s", method)
}
case *echo.Echo:
switch method {
case http.MethodGet:
e.GET(path, handler)
case http.MethodPost:
e.POST(path, handler)
case http.MethodPut:
e.PUT(path, handler)
case http.MethodDelete:
e.DELETE(path, handler)
case http.MethodPatch:
e.PATCH(path, handler)
case http.MethodHead:
e.HEAD(path, handler)
case http.MethodConnect:
e.CONNECT(path, handler)
case http.MethodOptions:
e.OPTIONS(path, handler)
case http.MethodTrace:
e.TRACE(path, handler)
default:
return fmt.Errorf("unsupported method: %s", method)
}
default:
return fmt.Errorf("engine type not supported")
}
return nil
}
// Start starts the server
func (s *Server) Start() {
host := fmt.Sprintf("%s:%s", s.host, s.port)
if len(s.port) == 0 {
host = s.host
}
go func() {
if err := s.echo.Start(host); err != nil && err != http.ErrServerClosed {
s.echo.Logger.Fatal(err)
}
}()
}
// GetEcho returns the Echo instance
func (s *Server) GetEcho() *echo.Echo {
return s.echo
}
// GetRouters returns all registered routes
func (s *Server) GetRouters() []*Route {
return s.echo.Routes()
}
// Close closes the server
func (s *Server) Close() error {
return s.echo.Close()
}
// Shutdown gracefully shuts down the server
func (s *Server) Shutdown(ctx context.Context) error {
return s.echo.Shutdown(ctx)
}
// GracefulShutdown shuts down the server with a timeout
func (s *Server) GracefulShutdown() error {
return s.gracefulShutdown()
}
func (s *Server) gracefulShutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return s.Shutdown(ctx)
}