如何在Golang中获取重定向URL而不是页面内容?

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

how to get the redirect url instead of page content in golang?

问题

我正在发送一个请求到服务器,但是它返回的是一个网页。有没有办法获取网页的URL呢?

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func main() {
  8. req, err := http.NewRequest("GET", "https://www.google.com", nil)
  9. if err != nil {
  10. panic(err)
  11. }
  12. client := new(http.Client)
  13. response, err := client.Do(req)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(ioutil.ReadAll(response.Body))
  18. }

我是你的中文翻译,以上是你要翻译的内容。

英文:

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?

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func main() {
  8. req, err := http.NewRequest("GET", "https://www.google.com", nil)
  9. if err != nil {
  10. panic(err)
  11. }
  12. client := new(http.Client)
  13. response, err := client.Do(req)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(ioutil.ReadAll(response.Body))
  18. }

答案1

得分: 25

你需要检查重定向并停止(捕获)它们。如果捕获到重定向,你可以使用响应结构的location方法获取重定向的URL(重定向到哪个URL)。

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. )
  7. func main() {
  8. req, err := http.NewRequest("GET", "https://www.google.com", nil)
  9. if err != nil {
  10. panic(err)
  11. }
  12. client := new(http.Client)
  13. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  14. return errors.New("Redirect")
  15. }
  16. response, err := client.Do(req)
  17. if err == nil {
  18. if response.StatusCode == http.StatusFound { //status code 302
  19. fmt.Println(response.Location())
  20. }
  21. } else {
  22. panic(err)
  23. }
  24. }

希望对你有帮助!

英文:

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.

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. )
  7. func main() {
  8. req, err := http.NewRequest("GET", "https://www.google.com", nil)
  9. if err != nil {
  10. panic(err)
  11. }
  12. client := new(http.Client)
  13. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  14. return errors.New("Redirect")
  15. }
  16. response, err := client.Do(req)
  17. if err == nil {
  18. if response.StatusCode == http.StatusFound { //status code 302
  19. fmt.Println(response.Location())
  20. }
  21. } else {
  22. panic(err)
  23. }
  24. }

huangapple
  • 本文由 发表于 2016年1月30日 00:13:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/35089052.html
匿名

发表评论

匿名网友

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

确定