Golang: Getting the response-redirect URL from an HTTP response

huangapple go评论68阅读模式
英文:

Golang: Getting the response-redirect URL from an HTTP response

问题

我正在尝试在Go语言中使用http.Get(url)进行HTTP请求,并且我想在浏览器中打开响应。我正在使用browser.OpenURL()来启动系统浏览器,但我无法弄清楚如何获取响应的URL。

在Python中,使用requests库,它是响应对象的一个属性。
我可以获取并在浏览器中打开它(使用browser库)的方式如下:

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

在Go语言中,如何实现这一点呢?响应对象是一个不包含该属性的结构体。

我正在尝试调用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,或者如何处理响应以便在浏览器中打开它?

英文:

I'm trying to make a HTTP request using http.Get(url) in Go and I want to open the response in a browser. I'm using browser.OpenURL() to launch the system browser, but I cannot figure out how to obtain the response url.

In Python, using the requests library, it is an attribute of the response object.
I can obtain and open it in a browser (using the browser library) like so:

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

How can I accomplish this using http/net library in Go? The response object is a struct that doesn't contain that attribute.

I am trying to call the Spotify API to authenticate an app, and this requires opening a browser window for user input. So far I've got this:

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)

Where can I obtain the response URL or how can I handle the response so that it opens it in a browser?

答案1

得分: 3

Go会在重定向时更新响应中的Request结构体。

resp.Request.URL是你要找的内容。

// Request是发送请求以获取此响应的请求。
// 请求的Body为nil(已被消耗)。
// 这仅适用于客户端请求。
Request *Request

英文:

Go will update the Request struct on the response if there is a redirect.

resp.Request.URL is what you are looking for.

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

得分: 0

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

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

Just get the redirect URL from response header.

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

huangapple
  • 本文由 发表于 2021年10月2日 05:32:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/69412160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定