如何通过调用Go语言中的URL来获取JSON对象?

问题描述 投票:3回答:2

我开始学习Golang,我想知道如何通过调用url来获得json响应,如果你能给我一个例子,那么为了引导自己会很好。

json http go request
2个回答
2
投票

我会写一个小帮手函数来做到这一点:

// 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

请注意,检查状态代码以及Get错误非常重要,并且必须明确关闭响应正文(请参阅此处的文档:http://golang.org/pkg/net/http/#Get


7
投票

这是一个简单的例子,可以帮助您入门。您应该考虑使用结构来保存请求的结果,而不是map [string] interface {}。

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "net/http"
)

func main() {
   resp, err := http.Get("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo")
   if err != nil {
      log.Fatal(err)
   }
   var generic map[string]interface{}
   err = json.NewDecoder(resp.Body).Decode(&generic)
   if err != nil {
      log.Fatal(err)
   }
   fmt.Println(generic)
}
© www.soinside.com 2019 - 2024. All rights reserved.