2

Redirection is divided into external redirection and internal redirection, and can also be divided into permanent redirection and temporary redirection.

External redirect

It can be achieved using the Redirect method, for example, if we want to permanently redirect to external Baidu:

 package main

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

func main() {
    r := gin.Default()
    r.GET("/index", func(c *gin.Context) {
        c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
    })
    r.Run(":9090")
}

The running result is directly redirected to external Baidu, we found that


Internal redirection

For example, if you want to jump from /a to /b, you can write:

 package main

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

func main() {
    r := gin.Default()
    r.GET("/index", func(c *gin.Context) {
        c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
    })
    r.GET("/a", func(c *gin.Context) {
        //跳转到/b对应的路由处理函数
        c.Request.URL.Path = "/b"
        r.HandleContext(c)
    })
    r.GET("/b", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "b",
        })
    })
    r.Run(":9090")
}

The result is as follows:


Reference: bilibili

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com