summaryrefslogtreecommitdiffstats
path: root/client/go/util
diff options
context:
space:
mode:
authorJon Bratseth <bratseth@gmail.com>2021-08-24 11:43:34 +0200
committerJon Bratseth <bratseth@gmail.com>2021-08-24 11:43:34 +0200
commit20ecdcec71d0443b5b5085c322dc9f48ad24c5a0 (patch)
tree75be32f3d8d957c8fd9e756440e56d79b1f41792 /client/go/util
parent4cf24301465f021893aa9439c20e4834760930b1 (diff)
JSON prettyprint responses
Diffstat (limited to 'client/go/util')
-rw-r--r--client/go/util/io.go12
-rw-r--r--client/go/util/print.go17
2 files changed, 19 insertions, 10 deletions
diff --git a/client/go/util/io.go b/client/go/util/io.go
index 217beb085d1..d7b849ba9a4 100644
--- a/client/go/util/io.go
+++ b/client/go/util/io.go
@@ -5,6 +5,7 @@
package util
import (
+ "bytes"
"errors"
"io"
"os"
@@ -24,8 +25,15 @@ func IsDirectory(path string) bool {
}
// Returns the content of a reader as a string
-func ReaderToString(reader io.ReadCloser) string {
+func ReaderToString(reader io.Reader) string {
buffer := new(strings.Builder)
io.Copy(buffer, reader)
return buffer.String()
-} \ No newline at end of file
+}
+
+// Returns the content of a reader as a byte array
+func ReaderToBytes(reader io.Reader) []byte {
+ buffer := new(bytes.Buffer)
+ buffer.ReadFrom(reader)
+ return buffer.Bytes()
+}
diff --git a/client/go/util/print.go b/client/go/util/print.go
index 7734a2a1a9e..91a223a3c3a 100644
--- a/client/go/util/print.go
+++ b/client/go/util/print.go
@@ -5,7 +5,8 @@
package util
import (
- "bufio"
+ "bytes"
+ "encoding/json"
"fmt"
"io"
"os"
@@ -40,13 +41,13 @@ func Detail(messages ...string) {
// Prints all the text of the given reader
func PrintReader(reader io.Reader) {
- // TODO: Pretty-print body
- scanner := bufio.NewScanner(reader)
- for ;scanner.Scan(); {
- Print(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- Error(err.Error())
+ bodyBytes := ReaderToBytes(reader)
+ var prettyJSON bytes.Buffer
+ parseError := json.Indent(&prettyJSON, bodyBytes, "", " ")
+ if parseError != nil { // Not JSON: Print plainly
+ Print(string(bodyBytes))
+ } else {
+ Print(string(prettyJSON.Bytes()))
}
}