如何通过Go语言中的url获取JSON对象? [英] How to get JSON object by calling a url in Go Language?

查看:676
本文介绍了如何通过Go语言中的url获取JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Golang,我想知道如何通过调用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.

推荐答案

我会写一个辅助函数来实现它:

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
}

可以在此处找到完整的工作示例: http://play.golang.org/p/b1WJb7MbQV

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

请注意,检查状态码和Get错误非常重要,并且必须明确关闭响应正文(请参见此处的文档:

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)

这篇关于如何通过Go语言中的url获取JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆