【六、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()
}
相关推荐
Macbethad1 小时前
DeviceNet主站程序技术方案
网络协议·信息与通信
8***29311 小时前
Go环境搭建(vscode调试)
开发语言·vscode·golang
多多*1 小时前
Threadlocal深度解析 为什么key是弱引用 value是强引用
java·开发语言·网络·jvm·网络协议·tcp/ip·mybatis
盛满暮色 风止何安2 小时前
WAF的安全策略
linux·运维·服务器·网络·网络协议·安全·网络安全
y***03172 小时前
Go基础之环境搭建
开发语言·后端·golang
武子康3 小时前
AI研究-133 Java vs Kotlin/Go/Rust/Python/Node:2025 详细对比分析 定位与取舍指南
java·javascript·python·golang·rust·kotlin·node
k***85843 小时前
Nginx中$http_host、$host、$proxy_host的区别
运维·nginx·http
apocelipes3 小时前
Linux的binfmt_misc机制
linux·c语言·c++·python·golang·linux编程·开发工具和环境
CodeByV4 小时前
【网络】HTTP协议深度解析:从请求响应到Cookie/Session
网络·网络协议·http
u***28474 小时前
golang debug调试
开发语言·后端·golang