【问题标题】:Cannot get correct json response using GoLang get使用 GoLang get 无法获得正确的 json 响应
【发布时间】:2014-12-20 00:48:43
【问题描述】:

我是 Go 新手,正在尝试编写一个简单的网络爬虫。我正在使用鸭鸭去的 api 并试图显示搜索结果。

https://duckduckgo.com/api

这是我的代码 - 主包

import (
    "fmt"
    "net/http"
)


func main() {
    getDuckDuckGo("food")
}

func getDuckDuckGo(keyword string) <- chan string{
    resp, _ := http.Get("http://api.duckduckgo.com/?q=" + keyword + "&format=json&pretty=1")
    c := make(chan string)


    fmt.Println(resp)
    var respMap map[string]interface{}
    fmt.Println(respMap)


    fmt.Println(respMap)
    return c
}

我的 resp println 给了我这个 -

&{200 OK 200 HTTP/1.1 1 1 map[Connection:[keep-alive] Content-Type:[application/x-javascript] Date:[Sat, 20 Dec 2014 00:41:49 GMT] Cache-Control:[max-age=1] Expires:[Sat, 20 Dec 2014 00:41:50 GMT] Server:[nginx] X-Duckduckgo-Locale:[en_US]] 0xf840053c20 -1 [chunked] false map[] 0xf84007c000}

而不是任何 json。

我的 GET 请求是否正确?

【问题讨论】:

  • 不要忽视你的错误!
  • 我对其进行了编辑以克服 go 错误 - 但我仍然得到相同的响应......所以我不确定你的意思?
  • 你的例子仍然没有对 http 响应做任何事情,并且打印了一个空的 respMap 两次。

标签: json go


【解决方案1】:

至少,你应该做以下事情:

  1. 检查http.Get()的错误
  2. 通过resp.Body 获取io.Reader 以获取HTTP 正文数据
  3. 使用json.Decoder解码json

你的getDuckDuckGo()应该变成这样:

func getDuckDuckGoImproved(k string) (map[string]interface{}, error) {
    resp, err := http.Get("http://api.duckduckgo.com/?=" + k + "&format=json")
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    r := make(map[string]interface{})
    d := json.NewDecoder(resp.Body)
    if err := d.Decode(&r); err != nil {
        return nil, err
    }
    return r, nil
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多