如何通过在Go Laguage中调用URL来获取JSON对象? [英] How to get JSON object by calling a url in Go Laguage?
问题描述
我开始学习Golang,我想知道如何通过调用url来获得json响应,如果你能给我一个例子,指导自己会很棒。
$ b
在此先感谢
我会写一个小帮助函数来执行此操作: / p>
// getJSON获取给定URL
的内容//并将其解码为JSON到给定结果中,
//应该是指向期望数据的指针。
func getJSON(url string,result interface {})错误{
resp,err:= http.Get(url)
if err!= nil {
return fmt.Errorf (无法获取URL%q:%v,url,err)
}
推迟resp.Body.Close()
如果resp.StatusCode!= http.StatusOK {
返回fmt.Errorf(意外的http GET状态:%s,resp.Status)
}
//如果需要,我们可以检查结果内容类型
//。
err:= json.NewDecoder(resp.Body).Decode(result)
if err!= nil {
return fmt.Errorf(无法解码JSON:%v,err)
返回无
$ $ $ $ $ $ $ $ $ $ $一个完整的工作例子可以在这里找到: http://play.golang.org/p/b1WJb7MbQV
请注意,检查状态代码以及Get错误非常重要,并且响应主体必须显式关闭(请参阅此处的文档: http://golang.org/pkg/net/http/#Get )
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.
Thanks in advance
解决方案 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)
这篇关于如何通过在Go Laguage中调用URL来获取JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!