gin-contrib / cors

Official CORS gin's middleware
https://gin-gonic.github.io/gin/
MIT License
1.77k stars 181 forks source link

c.Next() call missing in applyCors() function call #66

Closed uppalabharath closed 3 years ago

uppalabharath commented 4 years ago

Per gin's documentation every middleware should call c.Next() to pass the request to the next middleware registered. But I did not find the usage / call of Next() in any of the code.

May I know how this is working? Relevant code:

func (cors *cors) applyCors(c *gin.Context) {
    origin := c.Request.Header.Get("Origin")
    if len(origin) == 0 {
        // request is not a CORS request
        return
    }
    host := c.Request.Host

    if origin == "http://"+host || origin == "https://"+host {
        // request is not a CORS request but have origin header.
        // for example, use fetch api
        return
    }

    if !cors.validateOrigin(origin) {
        c.AbortWithStatus(http.StatusForbidden)
        return
    }

    if c.Request.Method == "OPTIONS" {
        cors.handlePreflight(c)
        defer c.AbortWithStatus(http.StatusNoContent) // Using 204 is better than 200 when the request status is OPTIONS
    } else {
        cors.handleNormal(c)
    }

    if !cors.allowAllOrigins {
        c.Header("Access-Control-Allow-Origin", origin)
    }
}
mqzabin commented 3 years ago

According to this, c.Next() has the sole purpose of run code below its call, after next handlers executions. Also, even if you run c.Next() conditionally, the next handler will run anyways. You should use c.Abort() or c.AbortWithStatus() in this case.

uppalabharath commented 3 years ago

Thanks @MatheusZabin