-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrafana.go
90 lines (74 loc) · 2.17 KB
/
grafana.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Range struct {
From time.Time `json:"from"`
To time.Time `json:"to"`
}
type Annotation struct {
Name string `json:"name"`
Datasource string `json:"datasource"`
IconColor string `json:"iconColor"`
Enable bool `json:"enable"`
Query string `json:"query"`
}
type AnnotationsRequest struct {
Annotation Annotation `json:"annotation"`
Range Range `json:"range"`
}
type AnnotationsResponse struct {
Annotation Annotation `json:"annotation"`
Time int64 `json:"time"`
Title string `json:"title"`
}
func annotations(res http.ResponseWriter, req *http.Request) {
var parsed AnnotationsRequest
if err := json.NewDecoder(req.Body).Decode(&parsed); err != nil {
http.Error(res, fmt.Sprintf("decode error %v", err), http.StatusBadRequest)
return
}
dataSource := req.Context().Value(ctxDataSourceKey).(*DataSource)
result, err := dataSource.AnnotationHandler(parsed)
if err != nil {
http.Error(res, fmt.Sprintf("%v", err), http.StatusBadRequest)
return
}
json.NewEncoder(res).Encode(&result)
}
func index(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "ok")
}
type AnnotationHandler func(req AnnotationsRequest) ([]AnnotationsResponse, error)
type DataSource struct {
AnnotationHandler AnnotationHandler
}
// HandleAnnotation assigns a function that will handle incoming annotation
// requests.
func (ds *DataSource) HandleAnnotation(fn AnnotationHandler) {
ds.AnnotationHandler = fn
}
type key int
const ctxDataSourceKey = key(1)
func withDataSource(next http.Handler, dataSource DataSource) http.Handler {
return http.HandlerFunc(
func(res http.ResponseWriter, req *http.Request) {
ctx := context.WithValue(req.Context(), ctxDataSourceKey, &dataSource)
req = req.WithContext(ctx)
next.ServeHTTP(res, req)
},
)
}
// ListenAndServe listens on the given address for incoming requests from
// grafana.
func (ds DataSource) ListenAndServe(addr string) error {
mux := http.NewServeMux()
mux.HandleFunc("/", index)
mux.HandleFunc("/annotations", annotations)
return http.ListenAndServe(addr, withDataSource(mux, ds))
}