为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
扬帆大鱼 2022-06-06 15:26:00
我试图在我的Handler函数上进行一些处理之后传递一些变量。我怎样才能redirect到一个新页面并将一些 json 变量传递给这个新模板?// main packagefunc main() {    apiRoutes := gin.Default()    apiRoutes.POST("api/ipg/send", controllers.GatewayIpgSendHandler)    apiRoutes.GET("ipg/:token", controllers.GatewayIpgRequestHandler)    // ... rest of the codes}// controllers packagefunc 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) 等价物。
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

您可以使用 cookie 或查询参数来传递变量。使用 中提供的解决方案之一GatewayIpgRequestHandler。


main.go


package main


import (

    "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()

}

控制器.go


package controllers


import (

    "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())

}


查看完整回答
反对 回复 2022-06-06
  • 1 回答
  • 0 关注
  • 227 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号