所以,我正在使用net/http包.我正在获取一个我确定知道重定向的URL.在登陆最终URL之前,它甚至可能会重定向几次.重定向在后台自动处理.
有没有简单的方法来确定最终的URL是什么,没有涉及在http.Client对象上设置CheckRedirect字段的hackish变通方法?
我想我应该提一下,我认为我想出了一个解决方法,但它有点像hackish,因为它涉及使用全局变量并在自定义http.Client上设置CheckRedirect字段.
必须有一个更清洁的方法来做到这一点.我希望这样的事情:
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)
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*erg 66
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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10270 次 |
| 最近记录: |