Home  >  Article  >  Backend Development  >  Unable to change POST request to GET request using Gin/GoLang

Unable to change POST request to GET request using Gin/GoLang

PHPz
PHPzforward
2024-02-10 19:45:08510browse

无法使用 Gin/GoLang 将 POST 请求更改为 GET 请求

php editor Baicao will introduce to you a common problem today, that is, how to change the POST request to a GET request when using the Gin/GoLang framework. Sometimes we may need to convert a POST request into a GET request, such as in some specific situations or for the convenience of testing. However, implementing this feature is not that simple and requires some tricks and code adjustments. Next, we will answer this question for you step by step and help you successfully complete this conversion.

Question content

I can't seem to change the post method with the get method in the gin framework. When I receive a request, I want to check it's credentials and, if valid, redirect to another page that has a get endpoint. Whenever I use c.request.method="get" it seems to only change the request for the current endpoint, but the redirected one still has the original method, which is the post method.

Code:

auth.GET("/sign-in", func(c *gin.Context) {
    c.File("../../html/index.html")
})

auth.POST("/sign-in", func(c *gin.Context) {
    c.Request.Method = "GET"
    c.Redirect(http.StatusTemporaryRedirect, "/profile/:pid")
})

code 307The request was originally a post request, which was changed to get by the endpoint itself.

Execution c.request.method="get" Not helpful. Can't find the answer either. Any idea how to change this behavior? Is creating a new request the only solution?

Solution

307 Status CodeDocumentation says:

The method and body of the original request are reused to perform the redirected request. If you wish to change the method used to GET, use 303 See Other instead.

So if you change http.StatusTemporaryRedirect to http.StatusSeeOther it will work without changing the original request method.

The above is the detailed content of Unable to change POST request to GET request using Gin/GoLang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete