dongpeng0127 2018-11-02 16:19
浏览 87
已采纳

如何将curl导入Go程序?

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('
')
    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?

  • 写回答

1条回答 默认 最新

  • douzhaolu4780 2018-11-02 19:06
    关注

    Regarding OP source code i would consider to change the condition to detect the presence of a pipe.

    As already provided in https://stackoverflow.com/a/43947435/4466350 the correct condition does not need to check for the length of the input. Thinking about it, this totally makes sense as you might open stdin without writing data on it.

    Besides the proposed solution seems uselessly complex for what it tries to achieve, pretty printing of a json input.

    I found out that using the standard library was sufficient to fulfill the goal for the given test case.

    About the question ...but how do I optimize my Go program to wait until curl is done?, it seems that OP does not understand the way the file descriptors are working. In fact, the question is not even correct, as the process could theoretically remain alive but actively decided to close Stdin. The OP is not interested in process liveliness, instead, he should simply look for EOF signal while reading Stdin, indicating that the interesting data was sent correctly.

    Anyways, a simple solution look likes this, wrap stdin with a json decoder, loop until eof or an error occur, for each decoded data, encode it to json with a wrapper of stdout, on error break again.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func main() {
        info, err := os.Stdin.Stat()
        if err != nil {
            log.Fatal(err)
        }
    
        if info.Mode()&os.ModeCharDevice != 0 {
            fmt.Println("The command is intended to work with pipes.")
            fmt.Println("cat file.json | prettyjson")
            return
        }
    
        dec := json.NewDecoder(os.Stdin)
        enc := json.NewEncoder(os.Stdout)
        enc.SetIndent("", "  ")
    
        for {
            data := map[string]interface{}{}
            if err := dec.Decode(&data); err != nil {
                if err == io.EOF {
                    break
                }
                log.Fatalf("decode error %v", err)
            }
            if err := enc.Encode(data); err != nil {
                log.Fatalf("encod error %v", err)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。