gpt4 book ai didi

http - 在golang中,如何确定一系列重定向后的最终URL?

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:19 24 4
gpt4 key购买 nike

所以,我正在使用 net/http 包。我正在获取一个我确定正在重定向的 URL。在到达最终 URL 之前,它甚至可能会重定向几次。重定向在后台自动处理。

有没有一种简单的方法可以找出最终的 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)
}

最佳答案

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

关于http - 在golang中,如何确定一系列重定向后的最终URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com