這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
如果短網址跳轉多次,需要特殊處理,checkRedirect函數會執行多次,返回的error類型會被封裝成url.Error類型,在GET方法的傳回值裡面可以對這個error做介面查詢,擷取傳回值,然後對這個傳回值做需要的處理。google group上別人的討論: https://groups.google.com/forum/#!topic/golang-china/RLdLq-pP6Hk
這種方法有一個需要注意的地方,當redictrect中途出錯的時候,返回的也是url.Error類型, 程式裡面要處理這種情況:
(*url.Error)(0x11a2c580)(Get http://refer.ly/aSpT: dial tcp 23.21.175.217:80: ConnectEx tcp: A connection attempt failed because the connected party did not properly respond aftera period of time, or established connection failed because connected host has failed to respond.)
package mainimport ("fmt""net/http""net/url"//"reflect""errors")var redirectCount int = 0func myRedirect(req *http.Request, via []*http.Request) (e error) {redirectCount++if redirectCount == 2 { //if strings.Index(str, "baidu") != -1 {//value := reflect.TypeOf(*req)//fmt.Print((value.Field(1).Name))//fmt.Println(req.URL.String())redirectCount = 0return errors.New(req.URL.String())}return }func main() {client := &http.Client{CheckRedirect: myRedirect}response, err := client.Get("http://t.co/R9iYVHVy52")if err != nil {if e, ok:= err.(*url.Error); ok && e.Err != nil {remoteUrl := e.URL//fmt.Println(e.Err)fmt.Println(remoteUrl)}}defer response.Body.Close()}