【六、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()
}
相关推荐
xcLeigh6 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
Bruce_Liuxiaowei7 小时前
轻量级 IOC 管理方案:Streamlit 驱动的恶意IP情报平台
网络·jvm·网络协议·tcp/ip·安全
techdashen14 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang
雾里0不看花16 小时前
.NET通过HTTP操作MINIO
http·.net·iphone
techdashen16 小时前
Go设计取舍之四: map不变时能否并发修改不同value
开发语言·后端·golang
名字还没想好☜16 小时前
Go 表驱动测试实战:用 t.Run 子测试组织可维护的单元测试
golang·单元测试·log4j·go·testing
golang学习记17 小时前
Claude Code写哪种变成语言最快?
golang·claude code
AI人工智能+电脑小能手17 小时前
【大白话说Java面试题 第210题】【10_网络协议篇】第1题:说说 TCP/IP 网络五层模型
java·网络协议·tcp/ip·计算机网络·网络五层模型
不在逃避q18 小时前
使用.NET实现自带思考的Tool 并且提供mcp streamable http服务
网络协议·http·.net
ShuiShenHuoLe18 小时前
Go html/template 使用入门
开发语言·golang·html