Gin框架重定向

Gin框架重定向

一、HTTP重定向

HTTP 重定向很容易。 内部、外部重定向均支持。

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	// http重定向
	r.GET("/index", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")

	})

	r.Run(":9999")
}

二、路由重定向

路由重定向,使用HandleContext

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	// 路由重定向
	r.GET("/home", func(c *gin.Context) {
		// 指定重定向路由
		c.Request.URL.Path = "/homeRedirect"

		// 继续后续处理
		r.HandleContext(c)
	})

	r.GET("/homeRedirect", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": "路由重定向",
		})
	})

	r.Run(":9999")
}

image-20211117222951540

原文地址:https://www.cnblogs.com/randysun/p/15626651.html