【六、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()
}
相关推荐
SZ1701102312 小时前
IP协议 标识字段 同一个源IP、目的IP和协议号内唯一
网络·网络协议·tcp/ip
海奥华23 小时前
go中的接口返回设计思想
开发语言·后端·golang
狐574 小时前
2025-06-02-IP 地址规划及案例分析
网络·网络协议·tcp/ip
飞川撸码7 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
利刃大大14 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
roman_日积跬步-终至千里15 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang
玩转4G物联网15 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
孔令飞15 小时前
Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践
ai·云原生·容器·golang·kubernetes
光芒Shine16 小时前
【物联网-ModBus-ASCII】
物联网·网络协议
hie9889416 小时前
HTTP常见的请求方法、响应状态码、接口规范介绍
http