-
Notifications
You must be signed in to change notification settings - Fork 60
/
serve_example_test.go
110 lines (92 loc) · 2.56 KB
/
serve_example_test.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package datasource_test
import (
"context"
"net/http"
"os"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/datasource"
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
"github.com/grafana/grafana-plugin-sdk-go/backend/resource/httpadapter"
)
type testDataSourceInstanceSettings struct {
httpClient *http.Client
}
func newDataSourceInstance(setting backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) {
return &testDataSourceInstanceSettings{
httpClient: &http.Client{},
}, nil
}
func (s *testDataSourceInstanceSettings) Dispose() {
// Cleanup
}
type testDataSource struct {
im instancemgmt.InstanceManager
}
func newDataSource() datasource.ServeOpts {
im := datasource.NewInstanceManager(newDataSourceInstance)
ds := &testDataSource{
im: im,
}
mux := http.NewServeMux()
mux.HandleFunc("/test", ds.handleTest)
return datasource.ServeOpts{
CheckHealthHandler: ds,
CallResourceHandler: httpadapter.New(mux),
QueryDataHandler: ds,
}
}
func (ds *testDataSource) getSettings(pluginContext backend.PluginContext) (*testDataSourceInstanceSettings, error) {
iface, err := ds.im.Get(pluginContext)
if err != nil {
return nil, err
}
return iface.(*testDataSourceInstanceSettings), nil
}
func (ds *testDataSource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) {
settings, err := ds.getSettings(req.PluginContext)
if err != nil {
return nil, err
}
// Handle request
resp, err := settings.httpClient.Get("http://")
if err != nil {
return nil, err
}
resp.Body.Close()
return nil, nil
}
func (ds *testDataSource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
var resp *backend.QueryDataResponse
err := ds.im.Do(req.PluginContext, func(settings *testDataSourceInstanceSettings) error {
// Handle request
resp, err := settings.httpClient.Get("http://")
if err != nil {
return err
}
resp.Body.Close()
return nil
})
return resp, err
}
func (ds *testDataSource) handleTest(rw http.ResponseWriter, req *http.Request) {
pluginContext := httpadapter.PluginConfigFromContext(req.Context())
settings, err := ds.getSettings(pluginContext)
if err != nil {
rw.WriteHeader(500)
return
}
// Handle request
resp, err := settings.httpClient.Get("http://")
if err != nil {
rw.WriteHeader(500)
return
}
resp.Body.Close()
}
func Example() {
err := datasource.Serve(newDataSource())
if err != nil {
backend.Logger.Error(err.Error())
os.Exit(1)
}
}