Description

When the gin engine's tree is not aware of a path /foo/ , instead of returning a 404, it responds plainly with a 307 Location: /foo (or 301 in case of GET) i.e. telling the client to redirect to /foo

There's no way to tell Gin what to do with such requests through the means any middlewares, like attaching CORS middlewares (a pretty commonly encountered case).

Some solutions I can think of: - Have a way to define what happens on redirect like we currently do with engine.NoRoute(..,) to explicitly define what happens at NotFound.

    server := gin.New()
    server.OnRedirect(cors.Default())
  • Apply the middlewares registered at the routerGroup "/" to all the incoming requests, including redirect request.
    server := gin.New()
    server.Use(cors.Default()) // registered at the "/" routergroup, therefore, redirect requests go through it as well

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/cors"
)

func main() {
    g := gin.Default()
        g.Use(cors.Default())
    g.GET("/foo", func(c *gin.Context) {
        c.String(200, "Hello, World!"))
    })
    g.Run(":9000")
}

Expectations

Open a new tab in the browser and open dev tools there. Go to the "Console", and run the following code

let response = await fetch('http://localhost:9000/foo/', {
  method: 'GET'
})

Expectation

response.text() should be "Hello World!"

Actual result

Access to fetch at 'http://localhost:9000/foo/' from origin 'chrome-extension://pejkokffkapolfffcgbmdmhdelanoaih' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Environment

  • go version: 1.22.0
  • gin version (or commit ref): 1.9.1
  • operating system: MacOS (Darwin ARM64)

Comment From: yashvardhan-kukreja

Raised the above PR #3858 as a resolution if the above issue is deemed worthy of having a solution.

Comment From: kbooz

Im facing this exactly same issue, every trailing slash redirection ignores all the cors headers on the browser, giving a cors Access-Control-Allow-Origin error

@yashvardhan-kukreja also thanks for the Medium blog post, it gave me more insight of what was happening

Comment From: yashvardhan-kukreja

Thanks @kbooz, appreciate your kind words :)

And yes, this issue was definitely a pain to deal with haha.

But yeah, feel free to use my fork (corresponding to the PR I raised) if it's something which you need to sorted out ASAP by go mod replace (as suggested in the blog).