Adding support for JSON-formatted output 1/n

This commit is contained in:
Juan Font Alonso 2021-05-08 13:28:22 +02:00
parent 4b3b48441f
commit 3b34f715ce
4 changed files with 89 additions and 11 deletions

View file

@ -1,6 +1,8 @@
package cli
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
@ -13,6 +15,10 @@ import (
"tailscale.com/tailcfg"
)
type ErrorOutput struct {
Error string
}
func absPath(path string) string {
// If a relative path is provided, prefix it with the the directory where
// the config file was found.
@ -72,3 +78,35 @@ func loadDerpMap(path string) (*tailcfg.DERPMap, error) {
err = yaml.Unmarshal(b, &derpMap)
return &derpMap, err
}
func jsonOutput(result interface{}, errResult error, outputFormat string) {
var j []byte
var err error
switch outputFormat {
case "json":
if errResult != nil {
j, err = json.MarshalIndent(ErrorOutput{errResult.Error()}, "", "\t")
if err != nil {
log.Fatalln(err)
}
} else {
j, err = json.MarshalIndent(result, "", "\t")
if err != nil {
log.Fatalln(err)
}
}
case "json-line":
if errResult != nil {
j, err = json.Marshal(ErrorOutput{errResult.Error()})
if err != nil {
log.Fatalln(err)
}
} else {
j, err = json.Marshal(result)
if err != nil {
log.Fatalln(err)
}
}
}
fmt.Println(string(j))
}