Skip to content

Commit 59ad0be

Browse files
committed
Plugin restapi: Implement a config callback.
1 parent 35f637c commit 59ad0be

File tree

2 files changed

+58
-18
lines changed

2 files changed

+58
-18
lines changed

restapi/README.md

+17
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,20 @@ Then build the plugin with the "c-shared" buildmode:
3434
```bash
3535
go build -buildmode=c-shared -o restapi.so
3636
```
37+
38+
## Configuration
39+
40+
### Synopsis
41+
42+
```
43+
LoadPlugin restapi
44+
<Plugin "restapi">
45+
Port "8080"
46+
</Plugin>
47+
```
48+
49+
### Options
50+
51+
* **Port** *Port*
52+
53+
Post to listen to. Defaults to `8080`.

restapi/restapi.go

+41-18
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"time"
1010

1111
"collectd.org/api"
12+
"collectd.org/config"
1213
"collectd.org/plugin"
1314
"go.uber.org/multierr"
1415
)
@@ -20,23 +21,10 @@ type restapi struct {
2021
}
2122

2223
func init() {
23-
mux := http.NewServeMux()
24-
mux.HandleFunc("/valueList", valueListHandler)
25-
26-
api := restapi{
27-
srv: &http.Server{
28-
Addr: ":8080",
29-
Handler: mux,
30-
},
31-
}
32-
33-
go func() {
34-
if err := api.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
35-
plugin.Errorf("%s plugin: ListenAndServe(): %v", pluginName, err)
36-
}
37-
}()
24+
ra := &restapi{}
3825

39-
plugin.RegisterShutdown(pluginName, api)
26+
plugin.RegisterConfig(pluginName, ra)
27+
plugin.RegisterShutdown(pluginName, ra)
4028
}
4129

4230
func valueListHandler(w http.ResponseWriter, req *http.Request) {
@@ -66,11 +54,46 @@ func valueListHandler(w http.ResponseWriter, req *http.Request) {
6654
}
6755
}
6856

69-
func (api restapi) Shutdown(ctx context.Context) error {
57+
func (ra *restapi) Configure(_ context.Context, rawConfig config.Block) error {
58+
fmt.Printf("%s plugin: rawConfig = %v\n", pluginName, rawConfig)
59+
60+
cfg := struct {
61+
Args string // unused
62+
Port string
63+
}{
64+
Port: "8080",
65+
}
66+
67+
if err := rawConfig.Unmarshal(&cfg); err != nil {
68+
return err
69+
}
70+
71+
mux := http.NewServeMux()
72+
mux.HandleFunc("/valueList", valueListHandler)
73+
74+
ra.srv = &http.Server{
75+
Addr: ":" + cfg.Port,
76+
Handler: mux,
77+
}
78+
79+
go func() {
80+
if err := ra.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
81+
plugin.Errorf("%s plugin: ListenAndServe(): %v", pluginName, err)
82+
}
83+
}()
84+
85+
return nil
86+
}
87+
88+
func (ra *restapi) Shutdown(ctx context.Context) error {
89+
if ra == nil || ra.srv == nil {
90+
return nil
91+
}
92+
7093
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
7194
defer cancel()
7295

73-
return api.srv.Shutdown(ctx)
96+
return ra.srv.Shutdown(ctx)
7497
}
7598

7699
func main() {} // ignored

0 commit comments

Comments
 (0)