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

标签 go

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

所以问题是如何找到 URL(如果客户端被重定向,则为最终 URL)? Response中没有这个字段.

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

最佳答案

虽然@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)

关于go - 如何在 http.go 中获取当前 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518945/

相关文章:

带有 Web 代理的 Golang Gorilla Websocket

go - 在 Go Routines 中测量时间

go - 在 Go 中深度复制图结构

go - gCloud 实例 : ssh: handshake failed: ssh: unable to authenticate, 尝试的方法 [无公钥],没有支持的方法

go - 不能在函数调用中使用某些类型

amazon-web-services - Golang 中 AWS S3 中的 NoCredentialproviders

xml - Golang rss xml解析 <atom10 :link overrides <link>

html/模板 : "xxx" is undefined error for one page but not the other

go - 如何将 json 解码为 [] 人?

regex - 如何在正则表达式中使整个单词可选?