英文:
how to get the redirect url instead of page content in golang?
问题
我正在发送一个请求到服务器,但是它返回的是一个网页。有没有办法获取网页的URL呢?
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://www.google.com", nil)
if err != nil {
panic(err)
}
client := new(http.Client)
response, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println(ioutil.ReadAll(response.Body))
}
我是你的中文翻译,以上是你要翻译的内容。
英文:
I am sending a request to server but it is returning a web page. Is there a way to get the url of the web page instead?
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://www.google.com", nil)
if err != nil {
panic(err)
}
client := new(http.Client)
response, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println(ioutil.ReadAll(response.Body))
}
答案1
得分: 25
你需要检查重定向并停止(捕获)它们。如果捕获到重定向,你可以使用响应结构的location方法获取重定向的URL(重定向到哪个URL)。
package main
import (
"errors"
"fmt"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://www.google.com", nil)
if err != nil {
panic(err)
}
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return errors.New("Redirect")
}
response, err := client.Do(req)
if err == nil {
if response.StatusCode == http.StatusFound { //status code 302
fmt.Println(response.Location())
}
} else {
panic(err)
}
}
希望对你有帮助!
英文:
You need to check for redirect and stop(capture) them. If you capture a redirection then you can get the redirect URL (to which redirection was happening) using location method of response struct.
package main
import (
"errors"
"fmt"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://www.google.com", nil)
if err != nil {
panic(err)
}
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return errors.New("Redirect")
}
response, err := client.Do(req)
if err == nil {
if response.StatusCode == http.StatusFound { //status code 302
fmt.Println(response.Location())
}
} else {
panic(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论