Alexander Kozachenko
Alexander Kozachenko

Reputation: 945

Why go server responds with 307 when CORS used

I have a very simple app with CORS middleware that seem to work correctly and preflight request works as expected. But for some reason server responds with 307 on actual request. Reproduces in browser, from postman works correclty.

func main() {
    router := gin.Default()
    router.Use(CORSMiddleware())

    accountsGroup := router.Group("/accounts")
    accountsGroup.POST("/", postAccount)
    router.Run("localhost:8080")
}

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Access-Control-Allow-Credentials", "true")
    c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")

    if c.Request.Method == "OPTIONS" {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
}


func postAccount(c *gin.Context) {
    response := gin.H{"id": 1}
    c.IndentedJSON(http.StatusCreated, response)
}

preflight response

preflight

actual request

actual request

server logs

[GIN-debug] Listening and serving HTTP on localhost:8080
[GIN] 2022/04/17 - 16:50:45 | 204 |            0s |       127.0.0.1 | OPTIONS  "/accounts"
[GIN-debug] redirecting request 307: /accounts/ --> /accounts/
[GIN] 2022/04/17 - 16:52:55 | 204 |            0s |       127.0.0.1 | OPTIONS  "/accounts"
[GIN-debug] redirecting request 307: /accounts/ --> /accounts/

Upvotes: 2

Views: 3431

Answers (1)

mkopriva
mkopriva

Reputation: 38303

You've registered the handler under /accounts/ but you're making the request to /accounts. That coupled with the RedirectTrailingSlash setting which is by default set to true is what causes the redirect.

Enables automatic redirection if the current route can't be matched but a handler for the path with (without) the trailing slash exists. For example if /foo/ is requested but a route only exists for /foo, the client is redirected to /foo with http status code 301 for GET requests and 307 for all other request methods.

Upvotes: 10

Related Questions