How to get redirect url instead of page content in golang?

I am sending a request to the server, but it returns a web page. Is there a way to get the url of a webpage?

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)) } 
+5
source share
1 answer

You need to check the redirection and stop (capture) them. If you commit the redirect, you can get the redirect URL (for which the redirect occurred) using the response structure method.

 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 err != nil { if response.StatusCode == http.StatusFound { //status code 302 fmt.Println(response.Location()) } else { panic(err) } } } 
+12
source

Source: https://habr.com/ru/post/1241829/


All Articles