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

因此,我正在使用net / http包。我正在获取一个我肯定知道要重定向的URL。在到达最终网址之前,它甚至可能重定向了几次。重定向在后台自动处理。

有没有一种简单的方法来确定最终的URL是什么,而没有涉及在http.Client对象上设置CheckRedirect字段的棘手的解决方法?

我想我应该提一提我想出了一种解决方法,但这有点of脚,因为它涉及使用全局变量并在自定义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

以上是 在golang中,如何在一系列重定向后确定最终的URL? 的全部内容, 来源链接: utcz.com/qa/401629.html

回到顶部