0

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

4

2 回答 2

3

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

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
于 2021-10-01T23:31:10.387 回答
0

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

redirectURL := resp.Header.Get("Location")
于 2021-10-02T11:26:18.823 回答