gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
76.73k stars 7.91k forks source link

Attach Response Headers (or middlewares) to redirected requests (CORS issues) #3857

Open yashvardhan-kukreja opened 4 months ago

yashvardhan-kukreja commented 4 months ago

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:

    server := gin.New()
    server.OnRedirect(cors.Default())

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

yashvardhan-kukreja commented 4 months ago

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