go | gin 重定向&路由重定向

web 重定向

重定向有一点要注意,重定向是在客户端那边执行的,一次服务器只能响应一次请求。但是要注意路由重定向
路由重定向是在服务器内部完成重定向资源请求

package main

import (
	"github.com/gin-gonic/gin"
	"fmt"
)

/*
func main() {
    r := gin.Default()

    r.GET("/test", func(c *gin.Context) {
        c.Redirect(302, "https://www.google.com")
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}
*/

/*
	curl -L -X POST http://localhost:8080/submit
	{"message":"hello, world"}hello, world.....

*/

func main() {
    
    
	r := gin.Default()

	r.POST("/submit", func(c *gin.Context) {
    
    
		// 处理 POST 请求

		c.Redirect(302, "/success")
	})

	r.POST("/success", func(c *gin.Context) {
    
    
		// c.String(200, "Success!")
		//c.JSON(200, gin.H{"message": "hello, world"})
		c.Header("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
		c.Header("Pragma", "no-cache")                                   // HTTP 1.0.
		c.Header("Expires", "0")    
		c.String(200, fmt.Sprintf("hello, world....."))
		
	})

	r.Run() // listen and serve on 0.0.0.0:8080
}


/*
	路由重定向
	使用 HandleContext

	 curl -L -X GET http://localhost:8080/test1			其中 -L 用于处理服务器返回的重定向,当服务器返回的3xx状态码时,使用了-L 参数,curl会自动重新发送请求到服务器在Location 头中指定新的URL
	hello, world... my name is zhangbuda....

*/

/*
func main(){
	r := gin.Default()

	r.GET("/test1", func(c *gin.Context){
		c.Request.URL.Path = "/test2"
		r.HandleContext(c)
	})

	r.GET("/test2", func(c *gin.Context){
		c.String(200, fmt.Sprintf("hello, world... my name is zhangbuda....\n"))
	})

	r.Run(":8080")
}
*/

经过抓包分析,下面介绍重定向

重定向

注意,如果要用curl 要让自动重定向,需要添加参数 -L
例如 curl -L -X POST url

在这里插入图片描述

再来分析,路由重定向

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ttxiaoxiaobai/article/details/137439489