mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
The Gin middleware is being used if one or more Origins are specified. Default setup for each Origin is as follows: - GET,POST, PUT, HEAD methods allowed - Credentials share disabled - Preflight requests cached for 12 hours Which are the defaults gin-contrib/cors comes with out of the box. Gin-cors will return a 403 if it gets a request with an Origin header that isn't on its' list. If no Origin header is specified then it will just return the servers response. Start fn with CORS enabled: `API_CORS="http://localhost:4000, http://localhost:3000" make run`
84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package cors
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type cors struct {
|
|
allowAllOrigins bool
|
|
allowCredentials bool
|
|
allowOriginFunc func(string) bool
|
|
allowOrigins []string
|
|
exposeHeaders []string
|
|
normalHeaders http.Header
|
|
preflightHeaders http.Header
|
|
}
|
|
|
|
func newCors(config Config) *cors {
|
|
if err := config.Validate(); err != nil {
|
|
panic(err.Error())
|
|
}
|
|
return &cors{
|
|
allowOriginFunc: config.AllowOriginFunc,
|
|
allowAllOrigins: config.AllowAllOrigins,
|
|
allowCredentials: config.AllowCredentials,
|
|
allowOrigins: normalize(config.AllowOrigins),
|
|
normalHeaders: generateNormalHeaders(config),
|
|
preflightHeaders: generatePreflightHeaders(config),
|
|
}
|
|
}
|
|
|
|
func (cors *cors) applyCors(c *gin.Context) {
|
|
origin := c.Request.Header.Get("Origin")
|
|
if len(origin) == 0 {
|
|
// request is not a CORS request
|
|
return
|
|
}
|
|
if !cors.validateOrigin(origin) {
|
|
c.AbortWithStatus(http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
cors.handlePreflight(c)
|
|
defer c.AbortWithStatus(200)
|
|
} else {
|
|
cors.handleNormal(c)
|
|
}
|
|
|
|
if !cors.allowAllOrigins {
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
|
}
|
|
}
|
|
|
|
func (cors *cors) validateOrigin(origin string) bool {
|
|
if cors.allowAllOrigins {
|
|
return true
|
|
}
|
|
for _, value := range cors.allowOrigins {
|
|
if value == origin {
|
|
return true
|
|
}
|
|
}
|
|
if cors.allowOriginFunc != nil {
|
|
return cors.allowOriginFunc(origin)
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (cors *cors) handlePreflight(c *gin.Context) {
|
|
header := c.Writer.Header()
|
|
for key, value := range cors.preflightHeaders {
|
|
header[key] = value
|
|
}
|
|
}
|
|
|
|
func (cors *cors) handleNormal(c *gin.Context) {
|
|
header := c.Writer.Header()
|
|
for key, value := range cors.normalHeaders {
|
|
header[key] = value
|
|
}
|
|
}
|