Golang Gin 使用新变量重定向和渲染模板

标签 go go-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.

}

Here is the php(laravel) equivalent我想做的事。

最佳答案

您可以使用 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()
}
Controller .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())
}

关于Golang Gin 使用新变量重定向和渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61970551/

相关文章:

go - 高并发下Go `net/http`的一些困惑

windows - 无法将 virtualKey 转换为 unicode

go - 错误:在services.GetCharactersID的参数中不能使用c.Param(“id”)(类型字符串)作为int类型。

go - Gin 框架无法从 Postman 获取数据

go - 未加载时如何忽略JSON输出中的关联字段?

go - 如何在 go gin-gonic 中创建 swagger.json

google-app-engine - 如何在 App Engine flex 环境和 Go 上正确启用 HTTPS?

go - 了解 Go 中的嵌入

Go 解析模板 glob

database - Redis连接池与Lambda