Golang Gin 重定向和渲染带有新变量的模板

我试图在我的Handler函数上进行一些处理之后传递一些变量。我怎样才能redirect到一个新页面并将一些 json 变量传递给这个新模板?


// main package

func main() {

    apiRoutes := gin.Default()

    apiRoutes.POST("api/ipg/send", controllers.GatewayIpgSendHandler)

    apiRoutes.GET("ipg/:token", controllers.GatewayIpgRequestHandler)


    // ... rest of the codes

}



// controllers package

func GatewayIpgRequestHandler(context *gin.Context) {

    // some processes that lead to these variables.

    wage := 123

    amount := 13123

    redirectUrl := "www.test.com/callback"



    // What should I do here to pass those

    // three variables above to an existing `custom-view.tmpl` file

    // in my `templates` folder.


}

这是我想做的 php(laravel) 等价物。


扬帆大鱼
浏览 228回答 1
1回答

qq_笑_17

您可以使用 cookie 或查询参数来传递变量。使用 中提供的解决方案之一GatewayIpgRequestHandler。main.gopackage mainimport (    "github.com/gin-gonic/gin"    "temp/controllers")func main() {    apiRoutes := gin.Default()    apiRoutes.GET("ipg/:token", controllers.GatewayIpgRequestHandler)    apiRoutes.GET("api/callback/cookies", controllers.APICallBackWithCookies)    apiRoutes.GET("api/callback/query_params", controllers.APICallBackWithQueryParams)    apiRoutes.Run()}控制器.gopackage controllersimport (    "github.com/gin-gonic/gin"    "net/http"    "net/url")func APICallBackWithCookies(c *gin.Context) {    wage, err := c.Cookie("wage")    if err != nil {        return    }    amount, err := c.Cookie("amount")    if err != nil {        return    }    c.JSON(http.StatusOK, gin.H{"wage": wage, "amount": amount})}func APICallBackWithQueryParams(c *gin.Context) {    wage := c.Query("wage")    amount := c.Query("amount")    c.JSON(http.StatusOK, gin.H{"wage": wage, "amount": amount})}func GatewayIpgRequestHandler(c *gin.Context) {    // first solution    c.SetCookie("wage", "123", 10, "/", c.Request.URL.Hostname(), false, true)    c.SetCookie("amount", "13123", 10, "/", c.Request.URL.Hostname(), false, true)    location := url.URL{Path: "/api/callback/cookies",}    c.Redirect(http.StatusFound, location.RequestURI())    // second solution    q := url.Values{}    q.Set("wage", "123")    q.Set("amount", "13123")    location := url.URL{Path: "/api/callback/query_params", RawQuery: q.Encode()}    c.Redirect(http.StatusFound, location.RequestURI())}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go