【六、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()
}
相关推荐
whhhhhhhhhw14 分钟前
Go语言常量
开发语言·后端·golang
望未来无悔3 小时前
HTTPS的概念和工作过程
网络协议·https
PineappleCoder4 小时前
为什么输入 URL 后会显示页面?HTTP 协议的 “幕后操作”
前端·http·面试
EndingCoder5 小时前
HTTP性能优化实战:解决高并发场景下的连接瓶颈与延迟问题
网络·网络协议·http·性能优化·高并发
IPIDEA全球IP代理5 小时前
IPIDEA:全球领先的企业级代理 IP 服务商
网络·网络协议·tcp/ip
十年一梦实验室5 小时前
工业机器人控制系统 IP-PP-EXEC 流水线
网络·人工智能·网络协议·tcp/ip·机器人
DemonAvenger6 小时前
Go中Protocol Buffers与JSON的网络数据序列化
网络协议·架构·go
zwxu_6 小时前
基于vscode连接服务器实现远程开发
java·开发语言·vscode·golang
郭二哈15 小时前
应⽤层协议HTTP
网络·网络协议·http
爱玩电脑的L15 小时前
网络原理 - TCP/IP
网络·网络协议·tcp/ip