-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Description
Feature Description
It's often helpful to set Access-Control-Allow-Origin response header value based on some conditions, for example, if the application is running in a test environment (specified by some arbitrary environment variable) then allow any port on localhost, you would be unable to use * as the value if you're also using Access-Control-Allow-Credentials: true.
In this scenario rather than having to specify every localhost with port origin you could potentially check whether the origin contains localhost which would return true and the implementation can then set the response header to the origin based on if this function returns true or false.
I was utilizing the fiber implementation of what * origin meant which was to not apply * but set whatever Origin header was set. This has been fixed as part of issue #2338.
So I am proposing a way that could be used to set the Access-Control-Allow-Origin header to whatever the origin is via a function. I am aware Gin has the AllowOriginFunc.
The implementation of using both AllowOrigins and this function could either be the function overwrites whatever is stored within AllowOrigins or it performs the origin checks on values specified in AllowOrigins first and the origin does not match any of these values then run the function.
Additional Context (optional)
If this feature gets accepted I am happy to work on it.
Code Snippet (optional)
package main
import "github.com/gofiber/fiber/v2"
import "github.com/gofiber/fiber/v2/middleware/cors"
import "log"
func main() {
app := fiber.New()
// Example 1 - check whether the origin is any scheme or port on localhost, this would result in any localhost app to access this app from the browser.
app.Use(cors.New(cors.Config{
AllowCredentials: true,
AllowOriginsFunc: func(origin string) bool {
return strings.Contains(origin, ":://localhost")
}
}))
// Example 2 - check whether the environment variable is set to "development", this would result in any origins being able to access this app from the browser.
app.Use(cors.New(cors.Config{
AllowCredentials: true,
AllowOriginsFunc: func(origin string) bool {
return os.Getenv("ENVIRONMENT") == "development"
}
}))
log.Fatal(app.Listen(":3000"))
}In both examples the Access-Control-Allow-Origin response header would be set to whatever the Origin request header is.
Checklist:
- I agree to follow Fiber's Code of Conduct.
- I have checked for existing issues that describe my suggestion prior to opening this one.
- I understand that improperly formatted feature requests may be closed without explanation.