duanjiashai9140
2018-01-02 11:23
浏览 149
已采纳

在JSON中设置标头获取请求

I'm getting JSON resonse from an external API with the following way:

func Request(url string, contentType string) []byte {
    resp, err := http.Get(url)
    resp.Header.Set("Content-Type", contentType)
    if err != nil {
        log.Fatal(err)
    }

    body, err := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }

    return body
}

url := fmt.Sprintf("https://example.com/api/category/%s", category)
contentType := "application/json"
body := Request(url, contentType)

res := &JSONRespStruct{}
err := json.Unmarshal([]byte(body), res)
if err != nil {
    log.Fatal(err)
}

The problem if I start to benchmark my site with go-wrk, the server crashes with the following error message:

2018/01/02 12:13:35 invalid character '<' looking for beginning of value

I think the code try to parse the JSON response as HTML. How I can force to get the response as a JSON?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dpqvwgr74759 2018-01-02 13:43
    最佳回答

    You probably want to set the header on the request. Setting the header on the response has no impact.

    func Request(url string, contentType string) []byte {
        req, err := http.NewRequest("GET", url, nil)
        if err != nil {
            log.Fatal(err)
        }
        req.Header.Set("Content-Type", contentType)
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        return body
    }
    
    评论
    解决 无用
    打赏 举报