如果短网址跳转多次,需要特殊处理,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 main import ( "fmt" "net/http" "net/url" //"reflect" "errors" ) var redirectCount int = 0 func 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 = 0 return 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() }原文链接:https://www.f2er.com/go/191067.html