如何获取http.go中的当前URL?

时间:2014-07-01 20:42:44

标签: go

我正在使用http.NewRequest发出几个http请求(显然)。现在我需要发出请求并从最终的URL中提取一些查询字符串(有一个重定向)。

所以问题是如何找到URL(如果客户端被重定向,是否为最终URL)? Response中没有此类字段。

请注意,我不需要停止重定向...只是为了找到请求后的URL

2 个答案:

答案 0 :(得分:3)

尽管@JimB实际上回答了我发布此问题的问题,因为它可能对某人有帮助。我使用过匿名函数。也许可以使用闭包更好地完成但我还没弄清楚闭包实际上是如何工作的。

req, err = http.NewRequest("GET", URL, nil)
cl := http.Client{}
var lastUrlQuery string
cl.CheckRedirect = func(req *http.Request, via []*http.Request) error {

    if len(via) > 10 {
        return errors.New("too many redirects")
    }
    lastUrlQuery = req.URL.RequestURI()
    return nil
}
resp, err := cl.Do(req)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("last url query is %v", lastUrlQuery)

答案 1 :(得分:2)

您向http.Client.CheckRedirect

添加回调
    // CheckRedirect specifies the policy for handling redirects.
    // If CheckRedirect is not nil, the client calls it before
    // following an HTTP redirect. The arguments req and via are
    // the upcoming request and the requests made already, oldest
    // first. If CheckRedirect returns an error, the Client's Get
    // method returns both the previous Response and
    // CheckRedirect's error (wrapped in a url.Error) instead of
    // issuing the Request req.
    //
    // If CheckRedirect is nil, the Client uses its default policy,
    // which is to stop after 10 consecutive requests.
    CheckRedirect func(req *Request, via []*Request) error

然后,您可以检查新请求。请确保设置某种限制以防止重定向循环(如文档中所述,10之后的默认中止)。