英文:
How to retrieve the final URL destination while using the http package in Go?
问题
大多数网站在请求期间会重定向到另一个URL。例如:http://example.com 可能会重定向到 http://mobile.example.com。
有没有办法获取最终的目标URL?在 cURL 中,他们称之为 effective URL。
英文:
Most sites redirect to another URL during a request. For example: http://example.com might might redirects to http://mobile.example.com
Is there a way to retrieve the final destination? In case of cURL, they call this the effective URL.
答案1
得分: 4
例如,
package main
import (
	"fmt"
	"net/http"
)
func main() {
	getURL := "http://pkgdoc.org/"
	fmt.Println("getURL:", getURL)
	resp, err := http.Get(getURL)
	if err != nil {
		fmt.Println(err)
		return
	}
	finalURL := resp.Request.URL.String()
	fmt.Println("finalURL:", finalURL)
}
输出:
getURL: http://pkgdoc.org/
finalURL: http://godoc.org/
英文:
For example,
package main
import (
	"fmt"
	"net/http"
)
func main() {
	getURL := "http://pkgdoc.org/"
	fmt.Println("getURL:", getURL)
	resp, err := http.Get(getURL)
	if err != nil {
		fmt.Println(err)
		return
	}
	finalURL := resp.Request.URL.String()
	fmt.Println("finalURL:", finalURL)
}
Output:
getURL: http://pkgdoc.org/
finalURL: http://godoc.org/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论