/
count.go
92 lines (73 loc) · 2.57 KB
/
count.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package handler
import (
"net/http"
"strconv"
"github.com/labstack/echo/v4"
"github.com/worldline-go/telemetry_example/internal/hold"
"github.com/worldline-go/telemetry_example/internal/msg"
"github.com/worldline-go/telemetry_example/internal/telemetry"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
)
type Handlers struct {
Counter *hold.Counter
}
func (h *Handlers) Register(group *echo.Group, middlewares []echo.MiddlewareFunc) {
group.GET("/count", h.GetCount, middlewares...)
group.POST("/count", h.PostCount, middlewares...)
}
// GetCount
//
// @Summary Get Count
// @Description Get Count
// @Produce json
// @Router /count [get]
// @Security ApiKeyAuth
// @Success 200 {object} msg.WebApiSuccess{}
// @Failure 400 {object} msg.WebApiError{}
func (h *Handlers) GetCount(c echo.Context) error {
_, span := otel.GetTracerProvider().Tracer(c.Path()).Start(c.Request().Context(), "GetCount")
defer span.End()
count := h.Counter.Get()
// Store n as a string to not overflow an int64.
span.SetAttributes(attribute.Int64("request.count.get", count))
telemetry.GlobalMeter.UpDownCounter.Add(c.Request().Context(), 1, metric.WithAttributes(telemetry.GlobalAttr...))
return c.JSON(http.StatusOK, msg.API{
Data: h.Counter.Get(),
})
}
// PostCount
//
// @Summary Add new count
// @Description Add new count
// @Produce json
// @Router /count [post]
// @Security ApiKeyAuth
// @Param count query int false "Count Value"
// @Success 200 {object} msg.WebApiSuccess{}
// @Failure 400 {object} msg.WebApiError{}
func (h *Handlers) PostCount(c echo.Context) error {
_, span := otel.GetTracerProvider().Tracer(c.Path()).Start(c.Request().Context(), "PostCount")
defer span.End()
countInt := int64(0)
count := c.QueryParam("count")
if count != "" {
var err error
countInt, err = strconv.ParseInt(count, 10, 64)
if err != nil {
return c.JSON(http.StatusBadRequest, msg.API{
Err: err.Error(),
})
}
}
span.SetAttributes(attribute.Key("request.count.set").Int64(countInt))
telemetry.GlobalMeter.SuccessCounter.Add(c.Request().Context(), 1, metric.WithAttributes(telemetry.GlobalAttr...))
telemetry.GlobalMeter.HistogramCounter.Record(c.Request().Context(), float64(countInt), metric.WithAttributes(telemetry.GlobalAttr...))
newResult := h.Counter.Add(countInt)
telemetry.WatchValue = newResult
telemetry.GlobalMeter.UpDownCounter.Add(c.Request().Context(), 1, metric.WithAttributes(telemetry.GlobalAttr...))
return c.JSON(http.StatusOK, msg.API{
Data: newResult,
})
}