|
1
|
|
|
package http |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"github.com/ansrivas/fiberprometheus/v2" |
|
5
|
|
|
"github.com/gofiber/contrib/otelfiber" |
|
6
|
|
|
"github.com/gofiber/fiber/v2" |
|
7
|
|
|
"github.com/gofiber/fiber/v2/middleware/cache" |
|
8
|
|
|
"github.com/gofiber/fiber/v2/middleware/cors" |
|
9
|
|
|
"github.com/gofiber/fiber/v2/middleware/favicon" |
|
10
|
|
|
"github.com/gofiber/fiber/v2/middleware/pprof" |
|
11
|
|
|
"github.com/gofiber/swagger" |
|
12
|
|
|
"github.com/memnix/memnix-rest/config" |
|
13
|
|
|
_ "github.com/memnix/memnix-rest/docs" // Side effect import |
|
14
|
|
|
) |
|
15
|
|
|
|
|
16
|
|
|
// New returns a new Fiber instance |
|
17
|
|
|
func New() *fiber.App { |
|
18
|
|
|
// Create new app |
|
19
|
|
|
|
|
20
|
|
|
app := fiber.New( |
|
21
|
|
|
fiber.Config{ |
|
22
|
|
|
Prefork: false, |
|
23
|
|
|
JSONDecoder: config.JSONHelper.Unmarshal, |
|
24
|
|
|
JSONEncoder: config.JSONHelper.Marshal, |
|
25
|
|
|
}) |
|
26
|
|
|
|
|
27
|
|
|
// Register middlewares |
|
28
|
|
|
registerMiddlewares(app) |
|
29
|
|
|
|
|
30
|
|
|
app.Get("/", func(c *fiber.Ctx) error { |
|
31
|
|
|
return c.SendString("Hello, World 👋!") |
|
32
|
|
|
}) |
|
33
|
|
|
|
|
34
|
|
|
// Use swagger middleware |
|
35
|
|
|
app.Get("/swagger/*", swagger.HandlerDefault) // default |
|
36
|
|
|
|
|
37
|
|
|
// Api group |
|
38
|
|
|
v2 := app.Group("/v2") |
|
39
|
|
|
|
|
40
|
|
|
v2.Get("/", func(c *fiber.Ctx) error { |
|
41
|
|
|
return fiber.NewError(fiber.StatusForbidden, "This is not a valid route") // Custom error |
|
42
|
|
|
}) |
|
43
|
|
|
|
|
44
|
|
|
registerRoutes(&v2) // /v2 |
|
45
|
|
|
|
|
46
|
|
|
return app |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
func registerMiddlewares(app *fiber.App) { |
|
50
|
|
|
// Use cors middleware |
|
51
|
|
|
app.Use(cors.New(cors.Config{ |
|
52
|
|
|
AllowOrigins: "http://localhost, *", |
|
53
|
|
|
AllowHeaders: "Origin, Content-Type, Accept, Authorization, Cache-Control", |
|
54
|
|
|
AllowCredentials: true, |
|
55
|
|
|
})) |
|
56
|
|
|
|
|
57
|
|
|
// Provide a minimal config |
|
58
|
|
|
app.Use(favicon.New(favicon.Config{ |
|
59
|
|
|
File: "./favicon.ico", |
|
60
|
|
|
URL: "/favicon.ico", |
|
61
|
|
|
})) |
|
62
|
|
|
|
|
63
|
|
|
app.Use(otelfiber.Middleware()) |
|
64
|
|
|
|
|
65
|
|
|
app.Use(cache.New(cache.Config{ |
|
66
|
|
|
Expiration: config.CacheExpireTime, |
|
67
|
|
|
CacheControl: true, |
|
68
|
|
|
Next: func(c *fiber.Ctx) bool { |
|
69
|
|
|
// Do not cache /metrics endpoint |
|
70
|
|
|
return c.Path() == "/metrics" |
|
71
|
|
|
}, |
|
72
|
|
|
})) |
|
73
|
|
|
|
|
74
|
|
|
prometheus := fiberprometheus.New("memnix") |
|
75
|
|
|
prometheus.RegisterAt(app, "/metrics") |
|
76
|
|
|
app.Use(prometheus.Middleware) |
|
77
|
|
|
|
|
78
|
|
|
app.Use(pprof.New()) |
|
79
|
|
|
} |
|
80
|
|
|
|