I want to write a little Go program I can use to beautify json data. It already works when I use a file. Here is the code:
package main
import (
"bufio"
"fmt"
"github.com/Jeffail/gabs"
"log"
"os"
)
func main() {
info, err := os.Stdin.Stat()
if err != nil {
log.Fatal(err)
}
if info.Mode()&os.ModeCharDevice != 0 || info.Size() <= 0 {
fmt.Println("The command is intended to work with pipes.")
fmt.Println("cat file.json | prettyjson")
return
}
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadBytes('\n')
if err != nil {
log.Fatal()
}
jsonParsed, err := gabs.ParseJSON(input)
if err != nil {
log.Fatal("couldn't parse json")
}
fmt.Println(fmt.Println(jsonParsed.StringIndent("", " ")))
}
If I run this code with with curl like this:
curl -s "https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD" | prettyjson
I get: (23) Failed writing body
I saw in this post that the pipe is being closed before curl can write all the data, but how do I optimize my Go program to wait until curl is done?