GolangNote

Golang笔记

Golang http client 处理重定向网页

Permalink

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。

处理重定向网页

默认请求

Go: http Get
1
2
3
4
5
6
7
8
9
10
func main(){
  resp, err := http.Get("http://www.golangnote.com/")

  if err != nil {
    fmt.Println(err)
  }

  fmt.Println("StatusCode:", resp.StatusCode)
  fmt.Println(resp.Request.URL)
}

结果是显示重定向后网址的状态:

plaintext: 输出
1
2
StatusCode: 200
https://golangnote.com/

禁用重定向

自定义 CheckRedirect 函数

Go: http 禁用重定向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func main(){
  client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
      return http.ErrUseLastResponse
  } }

  resp, err := client.Get("http://www.golangnote.com")

  if err != nil {
    fmt.Println(err)
    return
  }

  fmt.Println("StatusCode:", resp.StatusCode)
  fmt.Println(resp.Request.URL)
}

输出:

plaintext: output
1
2
StatusCode: 301
http://www.golangnote.com

跟踪重定向地址

写一个 for 循环跟踪重定网址

Go: loop for Redirect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func main() {
	myURL := "http://www.golangnote.com"
	nextURL := myURL
	var i int
	for i < 100 {
		client := &http.Client{
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				return http.ErrUseLastResponse
			}}

		resp, err := client.Get(nextURL)
		//resp, err := client.Head(nextURL)

		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Println("StatusCode:", resp.StatusCode)
		fmt.Println(resp.Request.URL)

		if resp.StatusCode == 200 {
			fmt.Println("Done!")
			break
		} else {
			nextURL = resp.Header.Get("Location")
			i += 1
		}
	}
}

输出

plaintext: output
1
2
3
4
5
6
7
StatusCode: 301
http://www.golangnote.com
StatusCode: 301
https://www.golangnote.com/
StatusCode: 405
https://golangnote.com/
Head "": unsupported protocol scheme ""

如果单纯的想跟踪重定向网址,可把 client.Get 改为 client.Head,状态码添加一个判断 resp.StatusCode == 405

本文网址: https://golangnote.com/topic/306.html 转摘请注明来源

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Write a Comment to "Golang http client 处理重定向网页"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms