This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
75 lines (66 loc) · 2 KB
/
server.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
package simplejson
import (
"net/http"
"github.com/clambin/go-common/httpserver/middleware"
"github.com/go-chi/chi/v5"
middleware2 "github.com/go-chi/chi/v5/middleware"
"github.com/go-http-utils/headers"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/exp/slog"
)
// Server receives SimpleJSON requests from Grafana and dispatches them to the handler that serves the specified target.
type Server struct {
chi.Router
Handlers map[string]Handler
prometheusMetrics *middleware.PrometheusMetrics
queryMetrics *QueryMetrics
logger *slog.Logger
}
var _ prometheus.Collector = &Server{}
var _ http.Handler = &Server{}
func New(handlers map[string]Handler, options ...Option) *Server {
s := Server{
Handlers: handlers,
Router: chi.NewRouter(),
logger: slog.Default(),
}
for _, o := range options {
o.apply(&s)
}
s.Router.Use(middleware2.Heartbeat("/"))
s.Router.Group(func(r chi.Router) {
r.Use(middleware.Logger(s.logger))
if s.prometheusMetrics != nil {
r.Use(s.prometheusMetrics.Handle)
}
r.Post("/search", s.Search)
r.Post("/query", s.Query)
r.Post("/annotations", s.Annotations)
r.Options("/annotations", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set(headers.AccessControlAllowOrigin, "*")
w.Header().Set(headers.AccessControlAllowMethods, "POST")
w.Header().Set(headers.AccessControlAllowHeaders, "accept, content-type")
})
r.Post("/tag-keys", s.TagKeys)
r.Post("/tag-values", s.TagValues)
})
return &s
}
// Describe implements the prometheus.Collector interface
func (s *Server) Describe(descs chan<- *prometheus.Desc) {
if s.prometheusMetrics != nil {
s.prometheusMetrics.Describe(descs)
}
if s.queryMetrics != nil {
s.queryMetrics.Describe(descs)
}
}
// Collect implements the prometheus.Collector interface
func (s *Server) Collect(metrics chan<- prometheus.Metric) {
if s.prometheusMetrics != nil {
s.prometheusMetrics.Collect(metrics)
}
if s.queryMetrics != nil {
s.queryMetrics.Collect(metrics)
}
}