如何在使用Go语言的http包时检索最终的URL目标?

huangapple go评论73阅读模式
英文:

How to retrieve the final URL destination while using the http package in Go?

问题

大多数网站在请求期间会重定向到另一个URL。例如:http://example.com 可能会重定向到 http://mobile.example.com

有没有办法获取最终的目标URL?在 cURL 中,他们称之为 effective URL

英文:

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.

答案1

得分: 4

例如,

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)
}

输出:

getURL: http://pkgdoc.org/
finalURL: http://godoc.org/
英文:

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/

huangapple
  • 本文由 发表于 2013年5月14日 06:50:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/16532436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定