Majid Alaeinia
Majid Alaeinia

Reputation: 1075

Golang Gin Redirect and Render a Template with New Variables

I am trying to pass some variables after some processes on my Handler function. How can I redirect to a new page an pass some json variables to this new template?

// 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 of what I want to do.

Upvotes: 11

Views: 21864

Answers (1)

You can use cookies or query parameters to pass variables. Use one of the solutions provided in 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())
}

Upvotes: 10

Related Questions