Home > front end >  Golang: Getting the response-redirect URL from an HTTP response
Golang: Getting the response-redirect URL from an HTTP response

Time:10-02

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?

CodePudding user response:

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

CodePudding user response:

Just get the redirect URL from response header.

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