Skip to content

Commit

Permalink
Add json flag
Browse files Browse the repository at this point in the history
The json flag returns the output as a JSON document like so:

```json
{
  "addresses": [
    "172.31.92.102",
    "172.31.34.208",
    "172.31.13.215"
  ]
}
```
  • Loading branch information
jasonwalsh committed Dec 30, 2018
1 parent 4715ef8 commit 405126b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
9 changes: 8 additions & 1 deletion cmd/discover/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import (
func main() {
var quiet bool
var help bool
var json bool
flag.BoolVar(&quiet, "q", false, "no verbose output")
flag.BoolVar(&help, "h", false, "print help")
flag.BoolVar(&json, "json", false, "output response as json")
flag.Parse()

d := &discover.Discover{}
Expand All @@ -42,5 +44,10 @@ func main() {
if err != nil {
l.Fatal(err)
}
fmt.Println(strings.Join(addrs, " "))
switch addrs.(type) {
case string:
fmt.Println(addrs)
case []string:
fmt.Println(strings.Join(addrs.([]string), " "))
}
}
16 changes: 14 additions & 2 deletions discover.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package discover

import (
"encoding/json"
"fmt"
"log"
"sort"
Expand Down Expand Up @@ -147,7 +148,7 @@ func (d *Discover) Help() string {
// Addrs discovers ip addresses of nodes that match the given filter criteria.
// The config string must have the format 'provider=xxx key=val key=val ...'
// where the keys and values are provider specific. The values are URL encoded.
func (d *Discover) Addrs(cfg string, l *log.Logger) ([]string, error) {
func (d *Discover) Addrs(cfg string, l *log.Logger) (interface{}, error) {
d.once.Do(d.initProviders)

args, err := Parse(cfg)
Expand Down Expand Up @@ -176,5 +177,16 @@ func (d *Discover) Addrs(cfg string, l *log.Logger) ([]string, error) {
return p.Addrs(args, l)
}

return p.Addrs(args, l)
addrs, err := p.Addrs(args, l)
if _, ok := args["json"]; ok {
r := map[string][]string{
"addresses": addrs,
}
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
return nil, fmt.Errorf("discover: unable to marshal response")
}
return string(b), err
}
return addrs, err
}

0 comments on commit 405126b

Please sign in to comment.