【问题标题】:Golang: Getting the response-redirect URL from an HTTP responseGolang:从 HTTP 响应中获取响应重定向 URL
【发布时间】:2021-11-23 11:20:24
【问题描述】:

我正在尝试在 Go 中使用 http.Get(url) 发出 HTTP 请求,并且我想在浏览器中打开响应。我正在使用 browser.OpenURL() 启动系统浏览器,但我不知道如何获取响应 url。

在 Python 中,使用 requests 库,它是响应对象的一个​​属性。 我可以像这样在浏览器中获取并打开它(使用浏览器库):

response = requests.get(endpoint)
browser.open(response.url)

如何在 Go 中使用 http/net 库来实现这一点?响应对象是一个不包含该属性的结构。

我正在尝试调用 Spotify API 来验证应用程序,这需要打开浏览器窗口以供用户输入。到目前为止,我得到了这个:

func getAuth(endpoint *url.Url) {
    request, _ := http.NewRequest("GET", endpoint.string(), nil)
    client := &http.Client{}
    resp, err := client.Do(request)
    if err != nil {
        panic(err)
    }
    headers := resp.Header
    page, _ := ioutil.ReadAll(resp.Body)

我在哪里可以获得响应 URL,或者如何处理响应以便它在浏览器中打开它?

【问题讨论】:

  • 在浏览器中打开originalurl,让浏览器处理重定向

标签: go go-http


【解决方案1】:

如果存在重定向,Go 将更新响应中的 Request 结构。

resp.Request.URL 就是你要找的东西。

// Request is the request that was sent to obtain this Response.
// Request's Body is nil (having already been consumed).
// This is only populated for Client requests.
Request *Request

【讨论】:

    【解决方案2】:

    只需从响应头中获取重定向 URL。

    redirectURL := resp.Header.Get("Location")
    

    【讨论】:

    • 我在查看响应对象的代码后尝试过,但是它没有返回值(至少在这种情况下)。 Response.Request.URL 确实返回了我正在寻找的 URL。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2013-12-04
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2011-05-15
    相关资源
    最近更新 更多