-
Notifications
You must be signed in to change notification settings - Fork 1
/
fiber.go
69 lines (62 loc) · 1.59 KB
/
fiber.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
package http
import (
"context"
"fmt"
"github.com/bytedance/sonic"
"github.com/gofiber/contrib/otelfiber"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/limiter"
"github.com/gofiber/fiber/v2/middleware/recover"
"go.uber.org/fx"
)
var (
FiberModule = fx.Module("fiber", FiberProviders, FiberInvokes)
FiberProviders = fx.Options(
fx.Provide(NewFiber),
fx.Provide(NewPromProbe),
fx.Provide(func(probe *PromProbe) Probe { return probe }),
)
FiberInvokes = fx.Options(
fx.Invoke(HookFiber),
)
)
type Probe interface {
Middleware(*fiber.Ctx) error
}
func NewFiber(config Config, probe Probe) *fiber.App {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: sonic.Marshal,
JSONDecoder: sonic.Unmarshal,
})
app.Use(otelfiber.Middleware())
app.Use(recover.New())
app.Use(compress.New(compress.Config{
Level: compress.LevelBestSpeed,
}))
app.Use(limiter.New(limiter.Config{
Max: config.Limiter.Requests,
Expiration: config.Limiter.Expiration,
LimiterMiddleware: limiter.SlidingWindow{},
}))
app.Use(probe.Middleware)
app.Use(cors.New())
return app
}
func HookFiber(lifecycle fx.Lifecycle, app *fiber.App, config Config) {
lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
go func() {
if err := app.Listen(fmt.Sprintf(":%d", config.Port)); err != nil {
panic(err)
}
}()
return nil
},
OnStop: func(context.Context) error {
return app.Shutdown()
},
})
}