Skip to content

Commit

Permalink
Plugin restapi: Implement a config callback.
Browse files Browse the repository at this point in the history
  • Loading branch information
octo committed May 18, 2020
1 parent 35f637c commit 6c6be63
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 18 deletions.
16 changes: 16 additions & 0 deletions restapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,19 @@ Then build the plugin with the "c-shared" buildmode:
```bash
go build -buildmode=c-shared -o restapi.so
```

## Configuration

### Synopsis

```
LoadPlugin restapi
<Plugin "restapi">
Port "8080"
</Plugin>
### Options
* **Port** *Port*
Post to listen to. Defaults to `8080`.
59 changes: 41 additions & 18 deletions restapi/restapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"collectd.org/api"
"collectd.org/config"
"collectd.org/plugin"
"go.uber.org/multierr"
)
Expand All @@ -20,23 +21,10 @@ type restapi struct {
}

func init() {
mux := http.NewServeMux()
mux.HandleFunc("/valueList", valueListHandler)

api := restapi{
srv: &http.Server{
Addr: ":8080",
Handler: mux,
},
}

go func() {
if err := api.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
plugin.Errorf("%s plugin: ListenAndServe(): %v", pluginName, err)
}
}()
ra := &restapi{}

plugin.RegisterShutdown(pluginName, api)
plugin.RegisterConfig(pluginName, ra)
plugin.RegisterShutdown(pluginName, ra)
}

func valueListHandler(w http.ResponseWriter, req *http.Request) {
Expand Down Expand Up @@ -66,11 +54,46 @@ func valueListHandler(w http.ResponseWriter, req *http.Request) {
}
}

func (api restapi) Shutdown(ctx context.Context) error {
func (ra *restapi) Configure(_ context.Context, rawConfig config.Block) error {
fmt.Printf("%s plugin: rawConfig = %v\n", pluginName, rawConfig)

cfg := struct {
Args string // unused
Port string
}{
Port: "8080",
}

if err := rawConfig.Unmarshal(&cfg); err != nil {
return err
}

mux := http.NewServeMux()
mux.HandleFunc("/valueList", valueListHandler)

ra.srv = &http.Server{
Addr: ":" + cfg.Port,
Handler: mux,
}

go func() {
if err := ra.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
plugin.Errorf("%s plugin: ListenAndServe(): %v", pluginName, err)
}
}()

return nil
}

func (ra *restapi) Shutdown(ctx context.Context) error {
if ra == nil || ra.srv == nil {
return nil
}

ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

return api.srv.Shutdown(ctx)
return ra.srv.Shutdown(ctx)
}

func main() {} // ignored

0 comments on commit 6c6be63

Please sign in to comment.