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

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

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

}

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:

确定