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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置