doulu2591 2014-01-01 21:48
浏览 501
已采纳

如何通过Go语言中的url获取JSON对象?

I'm starting to learn Golang and I would like to know how to get a json response by calling an url, if you could give me an example it would be great in order to guide myself.

  • 写回答

2条回答 默认 最新

  • douxing8939 2014-01-03 13:24
    关注

    I'd write a little helper function to do it:

    // getJSON fetches the contents of the given URL
    // and decodes it as JSON into the given result,
    // which should be a pointer to the expected data.
    func getJSON(url string, result interface{}) error {
        resp, err := http.Get(url)
        if err != nil {
            return fmt.Errorf("cannot fetch URL %q: %v", url, err)
        }
        defer resp.Body.Close()
        if resp.StatusCode != http.StatusOK {
            return fmt.Errorf("unexpected http GET status: %s", resp.Status)
        }
        // We could check the resulting content type
        // here if desired.
        err := json.NewDecoder(resp.Body).Decode(result)
        if err != nil {
            return fmt.Errorf("cannot decode JSON: %v", err)
        }
        return nil
    }
    

    A full working example can be found here: http://play.golang.org/p/b1WJb7MbQV

    Note that it is important to check the status code as well as the Get error, and the response body must be closed explicitly (see the documentation here: http://golang.org/pkg/net/http/#Get)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料