duanpu6319
2018-07-08 00:48
浏览 143
已采纳

如何在Golang中获得JWT的响应

I'm trying get the response from an API that uses JSON Web token, I need use the header : { Authorization: "Bearer token" } But I would like to keep the timeout of the http.Client that I'm using. How could I do it?

    var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dp709369831 2018-07-08 00:57
    最佳回答

    net/http.Request has a Header field that you can directly edit, but this means you can't use the shortcut client.Get method. Something more like:

    req, err := http.NewRequest(http.MethodGet, url, nil)
    if err != nil {
            return err
    }
    req.Header = map[string][]string{
            "Authorization": {fmt.Sprintf("Bearer %s", jwt)},
    }
    r, err := myClient.Do(req)
    ...
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题