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

一、http的重定向


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

cpp 复制代码
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()
}
相关推荐
apocelipes1 小时前
从源码角度解析C++20新特性如何简化线程超时取消
c++·性能优化·golang·并发·c++20·linux编程
Rinai_R7 小时前
Go 的调度模型
开发语言·后端·golang
福尔摩斯张8 小时前
插件式架构:解耦与扩展的艺术与实践(超详细)
linux·服务器·网络·网络协议·tcp/ip
Tony Bai8 小时前
Goroutine “气泡”宇宙——Go 并发模型的新维度
开发语言·后端·golang
YGGP10 小时前
【Golang】LeetCode 287. 寻找重复数
开发语言·leetcode·golang
吴佳浩 Alben10 小时前
Go 1.22 通关讲解
开发语言·数据库·golang
FserSuN10 小时前
TCP RST 与 Broken Pipe:从协议语义到操作系统信号的体系化梳理
网络·网络协议·tcp/ip
apihz11 小时前
全球IP归属地查询免费API详细指南
android·服务器·网络·网络协议·tcp/ip
fiveym11 小时前
PXE装机遇DHCP错误:ICMP echo reply导致IP分配失败原理解析
网络协议·tcp/ip·php
梁辰兴12 小时前
计算机网络基础:局域网的数据链路层
网络·网络协议·计算机网络·计算机·数据链路层·局域网·梁辰兴