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

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

PHPz
Release: 2024-02-10 19:45:08
forward
565 people have browsed it

无法使用 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")
})
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template