murli
murli

Reputation: 93

how to get the redirect url instead of page content in golang?

I am sending a request to server but it is returning a web page. Is there a way to get the url of the web page instead?

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://www.google.com", nil)
    if err != nil {
        panic(err)
    }

    client := new(http.Client)
    response, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    fmt.Println(ioutil.ReadAll(response.Body))
}

Upvotes: 9

Views: 14560

Answers (1)

Mayank Patel
Mayank Patel

Reputation: 8536

You need to check for redirect and stop(capture) them. If you capture a redirection then you can get the redirect URL (to which redirection was happening) using location method of response struct.

package main

import (
    "errors"
    "fmt"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "https://www.google.com", nil)
    if err != nil {
        panic(err)
    }
    client := new(http.Client)
    client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
        return errors.New("Redirect")
    }

    response, err := client.Do(req)
    if response != nil && response.StatusCode == http.StatusFound { //status code 302
        fmt.Println(response.Location())
    } else { // handle err or response == nil 
        fmt.Printf("rsp: %+v, err: %v\n", response, err)
    }
}

Upvotes: 27

Related Questions