-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_middleware_metric.go
54 lines (42 loc) · 1.13 KB
/
http_middleware_metric.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
package metrics
import (
"strconv"
"time"
"github.com/DIMO-Network/device-definitions-api/internal/infrastructure/exceptions"
"github.com/gofiber/fiber/v2"
"github.com/prometheus/client_golang/prometheus"
)
func HTTPMetricsPrometheusMiddleware(c *fiber.Ctx) error {
start := time.Now()
method := c.Route().Method
err := c.Next()
status := fiber.StatusInternalServerError
if err != nil {
if e, ok := err.(*fiber.Error); ok {
// Get correct error code from fiber.Error type
status = e.Code
}
if _, ok := err.(*exceptions.ValidationError); ok {
status = fiber.StatusBadRequest
}
if _, ok := err.(*exceptions.NotFoundError); ok {
status = fiber.StatusNotFound
}
if _, ok := err.(*exceptions.ConflictError); ok {
status = fiber.StatusConflict
}
} else {
status = c.Response().StatusCode()
}
path := c.Route().Name
statusCode := strconv.Itoa(status)
HTTPRequestCount.WithLabelValues(method, path, statusCode).Inc()
defer func() {
HTTPResponseTime.With(prometheus.Labels{
"method": method,
"path": path,
"status": statusCode,
}).Observe(time.Since(start).Seconds())
}()
return err
}