如何在Go中使用http包时检索最终的URL目标? [英] How to retrieve the final URL destination while using the http package in Go?
本文介绍了如何在Go中使用http包时检索最终的URL目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
http://example.com可能
可能会重定向到 http://mobile.example.com
有没有办法检索最终目的地?在 cURL
的情况下,他们将此称为有效URL
。
解决方案
例如,
包主
import(
fmt
net / http
)
func main(){
getURL:=http:// pkgdoc。 org /
fmt.Println(getURL:,getURL)
resp,err:= http.Get(getURL)
if err!= nil {
fmt.Println (err)
返回
}
finalURL:= resp.Request.URL.String()
fmt.Println(finalURL:,finalURL)
} $
$ b 输出: c $ c> getURL:http://pkgdoc.org/
finalURL:http://godoc.org/
Most sites redirect to another URL during a request. For example: http://example.com might
might redirects to http://mobile.example.com
Is there a way to retrieve the final destination? In case of cURL
, they call this the effective URL
.
解决方案
For example,
package main
import (
"fmt"
"net/http"
)
func main() {
getURL := "http://pkgdoc.org/"
fmt.Println("getURL:", getURL)
resp, err := http.Get(getURL)
if err != nil {
fmt.Println(err)
return
}
finalURL := resp.Request.URL.String()
fmt.Println("finalURL:", finalURL)
}
Output:
getURL: http://pkgdoc.org/
finalURL: http://godoc.org/
这篇关于如何在Go中使用http包时检索最终的URL目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文