In golang, how to determine the final URL after a series of redirects?

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

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) }

回答1:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!