How to get the redirected url in golang?

by mallory_cormier , in category: Third Party Scripts , a month ago

How to get the redirected url in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a month ago

@mallory_cormier 

In Golang, you can get the redirected URL by making an HTTP request and following the redirects until you reach the final destination URL. Here is an example code snippet that demonstrates how to get the redirected URL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
	"fmt"
	"net/http"
)

func getRedirectedURL(url string) (string, error) {
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	redirectedURL := resp.Request.URL.String()

	return redirectedURL, nil
}

func main() {
	url := "http://example.com"
	redirectedURL, err := getRedirectedURL(url)
	if err != nil {
		fmt.Println("Error getting redirected URL:", err)
		return
	}

	fmt.Println("Redirected URL:", redirectedURL)
}


In this code snippet, the getRedirectedURL function takes a URL as input and makes a GET request to that URL. The function then follows any redirects until it reaches the final destination URL. Finally, it returns the redirected URL.


You can run this code and replace the url variable with the URL you want to get the redirected URL for. The function will return the final redirected URL.