user6938349
user6938349

Reputation: 83

Using Gin: How to pass original JSON payload to a Redirect POST

I'm a newbie when it comes to Go and Gin, so please excuse my ignorance.

I've setup a server using Gin which supports a POST request. I would like the user to POST their request which includes a required JSON payload redirecting that request to another URL. As part of the redirect I need to pass the original JSON payload. For example, if the user issues this CURL request:

curl -H "Content-Type: application/json" -d '{ "name": "NewTest Network", "organizationId": 534238, "type": "wireless"}' -X POST "http://localhost:8080/network"

My Gin code does this:

r.POST("/network", func(c *gin.Context) {
    c.Redirect(http.StatusMovedPermanently, networks_url)
})

where: networks_url is the redirected URL. I need a way to pass the original JSON payload to the redirected URL.

Any help you could provide would be greatly appreciated.

Upvotes: 8

Views: 8389

Answers (4)

Mark Lakata
Mark Lakata

Reputation: 20907

The redirect feature of HTTP doesn't redirect anything. It just notifies the client that there is a new URL to use, and the client has to use the new URL instead of the old URL.

Use the -L option (--location) option to curl, and curl will do all the work for you.

curl -L -H "Content-Type: application/json" \
  -d '{ "name": "NewTest Network", "organizationId": 534238, "type": "wireless"}' \
  -X POST "http://localhost:8080/network"

Try running the same curl command with -v instead of -L, and you'll see that all of the redirection magic is in the response header.

Upvotes: 0

Vuong
Vuong

Reputation: 637

I've got the problem too many requests (loop), so I'm fine with this one.

if err != nil {
    session.AddFlash("The error I would like to show.", "error")
    c.Redirect(http.StatusMovedPermanently, "/my/route")
    return
}

Upvotes: 0

Ravishankar S R
Ravishankar S R

Reputation: 76

You must use 301 or 302 as a redirect status code.

c.Redirect(301, "http://www.google.com/")

Please refer the documentation here.

Upvotes: 3

Mr_Pink
Mr_Pink

Reputation: 109438

This doesn't have anything to do with Go or gin.

This is the expected behavior of a user agent, which should change the method from POST to GET with either a 301 or 302 redirect.

To instruct the user agent to repeat the request with the same method, use 307 (http.StatusTemporaryRedirect) or 308 (http.StatusPermanentRedirect).

Upvotes: 6

Related Questions