2013-05-28 21 views
18

所以,我使用網絡/ http包。我正在獲取一個我確定知道的URL重定向。它甚至可能重定向幾次,然後登錄到最終的URL。重定向在幕後自動處理。在golang中,如何確定一系列重定向後的最終URL?

有沒有一種簡單的方法來找出最終的網址是什麼,而沒有涉及在http.Client對象上設置CheckRedirect字段的黑客解決方法?

我想我應該提到,我想我想出了一個解決方法,但它有點駭人聽聞,因爲它涉及使用全局變量並在自定義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) 
} 
+0

對不起,我沒有一個真正的URL爲你一起工作。這是爲我的工作和我正在使用的網站需要憑據等 –

+3

可能重複[如何檢索最終的URL目標,而在Go中使用http包?](http://stackoverflow.com/questions/ 16532436/how-to-retrieve-the-final-url-destination-while-using-http-package-in-go) – peterSO

回答

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

輸出:

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 
+0

感謝您的迴應!它就像你展示的那樣對我有效。對不起,我花了很長時間纔將它標記爲正確的答案。一些高優先級的項目出現在工作中。 –

相關問題