forked from ori-shem-tov/algosearch
/
metrics.go
45 lines (32 loc) · 1.02 KB
/
metrics.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
package mid
import (
"context"
"net/http"
"github.com/kevguy/algosearch/backend/business/sys/metrics"
"github.com/kevguy/algosearch/backend/foundation/web"
)
// Metrics updates program counters.
func Metrics() web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// Add the metrics into the context for metric gathering.
ctx = metrics.Set(ctx)
// Call the next handler.
err := handler(ctx, w, r)
// Handle updating the metrics that can be handled here.
// Increment the request and goroutines counter.
metrics.AddRequests(ctx)
metrics.AddGoroutines(ctx)
// Increment if there is an error flowing through the request.
if err != nil {
metrics.AddErrors(ctx)
}
// Return the error so it can be handled further up the chain.
return err
}
return h
}
return m
}