在golang中,如何确定一系列重定向后的最终URL? [英] In golang, how to determine the final URL after a series of redirects?
问题描述
有没有一种简单的方法可以找出最终的URL,而不需要在http上设置CheckRedirect字段。客户端对象?
我想我应该提一下,我想我想出了一个解决方法,但它有点骇人听闻,因为它涉及到使用全局变量并设置CheckRedirect字段在一个自定义的http.Client。
有一个更干净的方法来做到这一点。
package main
import(
fmt
log
net / http
)
func main(){
//尝试获取一些重定向的URL。可能是5或6个看不见的重定向。
resp,err:= http.Get(http://some-server.com/a/url/that/redirects.html)
if err!= nil {
log .fatalf(http.Get =>%v,err.Error())
}
//找出我们最终以
结尾的URL finalURL:= magicFunctionThatTellsMeTheFinalURL(resp)
fmt.Printf(您结束的网址是:%v,finalURL)
}
package main
import(
fmt
log
net / http
)
func main(){
resp,err:= http.Get http://stackoverflow.com/q/16784419/727643)
if err!= nil {
log.Fatalf(http.Get =>%v,err.Error() )
}
//您的魔术功能。响应中的请求是
//客户端试图访问的最后一个URL。
finalURL:= resp.Request.URL.String()
fmt.Printf(你最终得到的URL是:%v \ n,finalURL)
}
输出:
您最终的网址是:http://stackoverflow.com/questions/16784419/in-golang-how-to-determine-the-final-url-after-a-series-of-重定向
So, I'm using the net/http package. I'm GETting a URL that I know for certain is redirecting. It may even redirect a couple of times before landing on the final URL. Redirection is handled automatically behind the scenes.
Is there an easy way to figure out what the final URL was without a hackish workaround that involves setting the CheckRedirect field on a http.Client object?
I guess I should mention that I think I came up with a workaround, but it's kind of hackish, as it involves using a global variable and setting the CheckRedirect field on a custom http.Client.
There's got to be a cleaner way to do it. I'm hoping for something like this:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
// Try to GET some URL that redirects. Could be 5 or 6 unseen redirections here.
resp, err := http.Get("http://some-server.com/a/url/that/redirects.html")
if err != nil {
log.Fatalf("http.Get => %v", err.Error())
}
// Find out what URL we ended up at
finalURL := magicFunctionThatTellsMeTheFinalURL(resp)
fmt.Printf("The URL you ended up at is: %v", finalURL)
}
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://stackoverflow.com/q/16784419/727643")
if err != nil {
log.Fatalf("http.Get => %v", err.Error())
}
// Your magic function. The Request in the Response is the last URL the
// client tried to access.
finalURL := resp.Request.URL.String()
fmt.Printf("The URL you ended up at is: %v\n", finalURL)
}
Output:
The URL you ended up at is: http://stackoverflow.com/questions/16784419/in-golang-how-to-determine-the-final-url-after-a-series-of-redirects
这篇关于在golang中,如何确定一系列重定向后的最终URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!