• 【六、http】go的http的客户端重定向


    一、http的重定向

    在这里插入图片描述
    重定向过程:客户浏览器发送http请求----》web服务器接受后发送302状态码响应及对应新的location给客户浏览器–》客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址----》服务器根据此请求寻找资源并发送给客户。在这里location可以重定向到任意URL,既然是浏览器重新发出了请求,则就没有什么request传递的概念了。在客户浏览器路径栏显示的是其重定向的路径,客户可以观察到地址的变化的。重定向行为是浏览器做了至少两次的访问请求的。

    package main
    
    import (
    	"errors"
    	"fmt"
    	"net/http"
    )
    
    func redirectLimitTimes() {
    	// 限制重定向的次数
    	client := &http.Client{
    		CheckRedirect: func(req *http.Request, via []*http.Request) error {
    			if len(via) > 10 {
    				return errors.New("redirect too times")
    			}
    			return nil
    		},
    	}
    
    	request, _ := http.NewRequest(
    		http.MethodGet,
    		"http://httpbin.org/redirect/20",
    		nil,
    	)
    	_, err := client.Do(request)
    	if err != nil {
    		panic(err)
    	}
    }
    
    func redirectForbidden() {
    	// 禁止重定向
    	// 登录请求,防止重定向到首页
    	client := &http.Client{
    		CheckRedirect: func(req *http.Request, via []*http.Request) error {
    			return http.ErrUseLastResponse
    		},
    	}
    
    	request, _ := http.NewRequest(
    		http.MethodGet,
    		"http://httpbin.org/cookies/set?name=poloxue",
    		nil,
    	)
    	r, err := client.Do(request)
    	if err != nil {
    		panic(err)
    	}
    	defer func() {_ = r.Body.Close()}()
    	fmt.Println(r.Request.URL)
    }
    
    func main() {
    	// 重定向
    	// 返回一个状态码,3xx 301 302 303 307 308
    	redirectForbidden()
    }
    
    • 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
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
  • 相关阅读:
    postgresql pgsql 连接池 pgBouncer(详细)
    [linux学习笔记]02 gcc安装与使用
    BMP编程实践1:C语言实现bmp位图分析与创建
    四、Vue3基础四
    html简单案例
    预测性人工智能会彻底改变SIEM行业吗?
    Python基础学习笔记【最好拥有一定Java基础】
    存在重复元素(C++解法)
    动态规划-矩阵连乘
    用Tinyproxy搭建自己的proxy server
  • 原文地址:https://blog.csdn.net/qq_39852676/article/details/134212786