-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
449 lines (386 loc) · 12.8 KB
/
engine.go
File metadata and controls
449 lines (386 loc) · 12.8 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package httpbara
import (
"context"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gopybara/httpbara/casual"
"net/http"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
)
// core is the main engine implementation that consolidates routes, groups, and middleware
// extracted by Handler instances. It sets up the Gin engine, applies all handlers, and runs the server.
// The 'core' type implements the Engine interface.
//
// Fields:
// - Params: A configuration object containing parameters for the engine (implementation details omitted).
// - flatGroups: A map of group names to Group objects. Each Group represents a set of related routes sharing a common prefix and middlewares.
// - flatMiddlewares: A map of middleware names to Middleware objects. Each middleware can also apply additional middleware.
// - flatRoutes: A slice of Route objects representing all routes extracted from Handler instances.
type core struct {
params
flatGroups map[string]*Group
flatMiddlewares map[string]*Middleware
flatRoutes []*Route
}
// Engine defines the interface for an HTTP engine capable of registering routes, groups, and middleware
// and running the server. Implementations should integrate with a Gin engine.
//
// Methods:
// - flatHandlers([]*Handler): Process a collection of Handler objects to flatten their routes, groups, and middleware.
// - applyHandlers(): Apply all collected routes, groups, and middleware to the underlying Gin engine.
// - Run(addr string) chan error: Run the HTTP server at the specified address and return a channel for errors.
type Engine interface {
flatHandlers(handlers []*Handler)
applyHandlers()
Run(addr string) error
}
// New creates a new Engine (core implementation) given a list of Handler objects
// and optional parameters. Handlers usually come from the logic of `NewHandler` (not shown here),
// which reflectively extracts routes, groups, and middleware from a user-defined struct.
//
// Parameters:
// - handlers: A slice of Handler objects containing routes, groups, and middleware definitions.
// - opts: A list of options (param functions) that configure the engine (e.g., setting a custom Gin instance or logger).
//
// Returns:
// - Engine: a configured engine ready to register routes and run.
// - error: If any configuration step fails, an error is returned.
//
// Example usage:
// ```go
// engine, err := New([]*Handler{handler1, handler2}, WithCustomLogger(myLogger))
//
// if err != nil {
// log.Fatal(err)
// }
//
// err := engine.Run(":8080")
// // waiting for error
// ```
func New(handlers []*Handler, opts ...ParamsCb) (Engine, error) {
c := &core{
flatGroups: make(map[string]*Group),
flatMiddlewares: make(map[string]*Middleware),
flatRoutes: make([]*Route, 0),
}
c.params.shutdownTimeout = 30 * time.Second
for _, opt := range opts {
err := opt(&c.params)
if err != nil {
return nil, fmt.Errorf("failed to apply option: %w", err)
}
}
// Create a base Gin engine if none was provided
if c.gin == nil {
err := c.createBaseGin()
if err != nil {
return nil, fmt.Errorf("failed to create base gin engine: %w", err)
}
}
if c.casualResponseHandler == nil {
c.casualResponseHandler = defaultCasualResponder[any]
}
if c.casualResponseErrorHandler == nil {
c.casualResponseErrorHandler = defaultCasualErrorResponder
}
// Set a default logger if none provided
if c.log == nil {
c.log = NewFmtLogger()
}
c.flatHandlers(handlers)
c.applyHandlers()
return c, nil
}
// flatHandlers processes the given list of Handler objects and flattens their groups, middlewares, and routes
// into core's internal maps and slices. This prepares all routing information to be later applied to the Gin engine.
//
// Parameters:
// - handlers: A slice of Handler objects, each containing discovered routes, groups, and middleware.
//
// After this method is called, `flatGroups`, `flatMiddlewares`, and `flatRoutes` will be populated.
func (c *core) flatHandlers(handlers []*Handler) {
for _, handler := range handlers {
c.flatRoutes = append(c.flatRoutes, handler.routes...)
for _, casualR := range handler.casualRoutes {
useGinContext := false
if casualR.handler.rm.Type.In(1) == reflect.TypeOf((*gin.Context)(nil)) {
useGinContext = true
}
reqType := casualR.handler.rm.Type.In(2)
cb := func(ctx *gin.Context) {
rcb := getResponseCallback(ctx)
var ct = ctx.Request.Context()
if useGinContext {
ct = ctx
}
reqVal, err := dynamicBind(ctx, reqType)
if err != nil {
rcb(c.casualResponseErrorHandler(err))
ctx.Abort()
return
}
var arg reflect.Value
switch reqType.Kind() {
case reflect.Struct:
// handler.Handle(ctx, req contracts.PublishEventsEvent[…])
// ждёт сам struct, разворачиваем указатель
arg = reqVal.Elem()
case reflect.Ptr:
// handler.Handle(ctx, req *contracts.PublishEventsEvent[…])
// ждёт pointer, передаём reqVal
arg = reqVal
default:
c.log.Panic("unexpected reqType kind", "kind", reqType.Kind().String())
}
respArr := casualR.handler.rm.Func.Call([]reflect.Value{*casualR.handler.rv, reflect.ValueOf(ct), arg})
statusCode := http.StatusOK
if respArr[0].MethodByName("StatusCode").IsValid() {
values := respArr[0].MethodByName("StatusCode").Call([]reflect.Value{})
statusCode = values[0].Interface().(int)
}
paramsCbs := []casual.HttpResponseParamsCb{
casual.WithHttpStatusCode(statusCode),
}
switch len(respArr) {
case 1:
if respArr[0].IsNil() {
ctx.AbortWithStatus(statusCode)
return
}
rcb(c.params.casualResponseErrorHandler(respArr[0].Interface().(error)))
ctx.Abort()
return
case 2:
if respArr[1].IsNil() {
if !respArr[1].IsNil() {
rcb(c.casualResponseErrorHandler(respArr[1].Interface().(error)))
ctx.Abort()
return
}
if respArr[0].MethodByName("Meta").IsValid() &&
respArr[0].MethodByName("Meta").Type().NumIn() == 0 &&
respArr[0].MethodByName("Meta").Type().NumOut() == 1 &&
respArr[0].MethodByName("Meta").Type().Out(0).Kind() == reflect.Map {
values := respArr[0].MethodByName("Meta").Call([]reflect.Value{})
dataMap := make(map[string]interface{})
next := values[0].MapRange()
for {
if !next.Next() {
break
}
dataMap[next.Key().String()] = next.Value().Interface()
}
paramsCbs = append(paramsCbs, casual.WithMeta(dataMap))
}
rcb(c.params.casualResponseHandler(respArr[0].Interface(), paramsCbs...))
ctx.Abort()
} else {
rcb(c.params.casualResponseErrorHandler(respArr[1].Interface().(error)))
ctx.Abort()
return
}
default:
c.log.Panic(
"casual handler returned more than two values",
"handler", casualR.handler.rm.Name,
"route", casualR.path,
"method", casualR.method)
}
}
c.flatRoutes = append(c.flatRoutes, &Route{
method: casualR.method,
path: casualR.path,
handler: cb,
middlewares: casualR.middlewares,
group: casualR.group,
})
}
for _, group := range handler.groups {
c.flatGroups[group.name] = group
}
for _, middleware := range handler.middlewares {
c.flatMiddlewares[strings.ToLower(middleware.middleware)] = middleware
}
}
}
func dynamicBind(ctx *gin.Context, reqType reflect.Type) (reflect.Value, error) {
base := reqType
for base.Kind() == reflect.Ptr {
base = base.Elem()
}
if base.Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("dynamicBind: expected struct type, got %s", base.Kind())
}
reqPtr := reflect.New(base)
var binder func(interface{}) error
contentType := ctx.ContentType()
switch {
case strings.HasSuffix(contentType, "json"):
binder = ctx.ShouldBindJSON
case strings.HasSuffix(contentType, "xml"):
binder = ctx.ShouldBindXML
case strings.HasSuffix(contentType, "yaml"):
binder = ctx.ShouldBindYAML
default:
binder = ctx.ShouldBind
}
if err := binder(reqPtr.Interface()); err != nil {
return reflect.Value{}, err
}
return reqPtr, nil
}
type responseCallback func(code int, obj any)
func getResponseCallback(ctx *gin.Context) responseCallback {
switch ctx.GetHeader("Accept") {
case "application/xml":
return ctx.XML
default:
return ctx.JSON
}
}
// applyHandlers goes through all flattened routes and applies them to the Gin engine.
// It reconstructs the full path by combining group prefixes (if any) and sets up the middleware stack.
// Middleware can be defined at the group level and at the route level. If a route belongs to a group,
// the group's middleware is applied first, followed by the route's middleware.
//
// This method also logs warnings if a specified group or middleware cannot be found,
// and logs info messages about successful route registrations.
func (c *core) applyHandlers() {
for _, route := range c.flatRoutes {
path := route.path
handleStack := make([]gin.HandlerFunc, 0)
for _, mw := range c.rootMiddlewares {
for _, middleware := range mw.middlewares {
handleStack = append(handleStack, middleware.handler)
}
}
// Apply group prefix and group-level middleware if route has a group
if route.group != "" {
if group, ok := c.flatGroups[route.group]; ok {
path = strings.TrimSuffix(group.Path, "/") + "/" + strings.TrimPrefix(path, "/")
for _, m := range group.middlewares {
if mw, mwOk := c.flatMiddlewares[m]; mwOk {
handleStack = append(handleStack, mw.handler)
} else {
c.log.Warn("skipping group middleware because there is no middleware with this name",
"middlewareToSkip", m,
"group", route.group,
)
}
}
} else {
c.log.Warn("skipping group because group was not found",
"path", route.path,
"group", route.group,
)
}
}
var appliedMiddlewares []string
for _, middleware := range route.middlewares {
if mw, ok := c.flatMiddlewares[middleware]; ok {
appliedMiddlewares = append(appliedMiddlewares, mw.middleware)
// Some middleware can apply additional middleware
for _, m := range mw.middlewares {
if mw2, mw2ok := c.flatMiddlewares[m]; mw2ok {
handleStack = append(handleStack, mw2.handler)
} else {
c.log.Warn("skipping middleware of middleware because there is no middleware with this name",
"route", path,
"middlewareToSkip", m,
"parentMiddleware", mw.middleware,
)
}
}
handleStack = append(handleStack, mw.handler)
} else {
c.log.Warn("skipping route middleware because there is no middleware with this name",
"route", path,
"middlewareToSkip", middleware,
)
}
}
handleStack = append(handleStack, route.handler)
if route.method == "ANY" {
c.gin.Any(path, handleStack...)
} else {
c.gin.Handle(route.method, path, handleStack...)
}
c.log.Info("route was registered",
"method", route.method,
"route", path,
"middlewares", appliedMiddlewares,
)
}
}
// createBaseGin initializes a new default Gin engine with standard middleware (like Recovery).
// If a custom Gin instance was not provided via parameters, this method ensures there's at least
// a basic setup to work with.
//
// Returns:
// - error: If initialization fails for some reason (unlikely).
func (c *core) createBaseGin() error {
c.gin = gin.New()
c.gin.Use(gin.Recovery())
return nil
}
// Run starts the HTTP server on the given address using the underlying Gin engine.
// It returns a channel of errors, allowing the caller to handle any runtime server errors asynchronously.
//
// Parameters:
// - addr: The address to listen on, e.g., ":8080" for port 8080.
//
// Returns:
// - chan error: A channel that will receive any error that occurs when running the server.
//
// Example:
// ```go
// engine, _ := New(handlers)
// errChan := engine.Run(":8080")
//
// if err := <-errChan; err != nil {
// log.Fatal("server error:", err)
// }
//
// ```
func (c *core) Run(addr string) error {
errChan := make(chan error)
srv := &http.Server{
Addr: addr,
Handler: c.gin,
}
go func() {
errChan <- func() error {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}()
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-errChan:
if err != nil {
return fmt.Errorf("server failed to start: %w", err)
}
case sig := <-quit:
c.log.Info("shutting down server", "signal", sig)
ctx, cancel := context.WithTimeout(context.Background(), c.shutdownTimeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
return fmt.Errorf("server shutdown failed: %w", err)
}
if c.taskTracker != nil {
if err := c.taskTracker.Shutdown(ctx); err != nil {
return fmt.Errorf("task tracker shutdown failed: %w", err)
}
}
}
return nil
}