【六、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()
}
相关推荐
qinaoaini3 小时前
[golang][MAC]Go环境搭建+VsCode配置
vscode·macos·golang
花酒锄作田4 小时前
Go - slog使用入门
golang
u***35744 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
雨天行舟7 小时前
abap调用deepseek接口 v3.0
http·ai·sap·abap·聊天·deepseek
小同志007 小时前
网络原理 -KTTP/HTTPS(五) --认识响应“报头“(header) / “正⽂“(body)
java·网络·网络协议·http·https
好家伙VCC8 小时前
# 发散创新:基于 Go 语言打造高性能服务网格的实践与突破在微服务架构
java·python·微服务·架构·golang
unirst19850079 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
YGGP9 小时前
【Golang】LeetCode 3. 无重复字符的最长子串
开发语言·leetcode·golang
xuxg20059 小时前
4G AT命令解析框架LwAtParser V2.0设计及实现(基于uCOS II)--中级篇 第七章 TCP协议实现
网络·网络协议·tcp/ip
大黄说说10 小时前
Go 实战 LeetCode 151:高效翻转字符串中的单词(含空格处理技巧)
开发语言·leetcode·golang