iris-contrib / middleware

Community Middleware List for the Iris Web Framework.
https://github.com/kataras/iris
240 stars 91 forks source link

cors should Change the way #58

Open hanyue2019 opened 4 years ago

hanyue2019 commented 4 years ago

I have try the middleware,but it does not work I find an easy way to handle this,maybe you can change I copy from https://studygolang.com/articles/25389

crs := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
        AllowCredentials: true,
    })
app:= iris.New()
app.Use(crs())

unlike

crs := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
        AllowCredentials: true,
    })

    v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)`
kataras commented 4 years ago

Hello @hanyue2019 , the method you described in the article, is also described at: https://github.com/kataras/iris/blob/8359c9a0f5b0eadfc16ae24f879b477a18a8b9a4/_examples/experimental-handlers/cors/simple/main.go#L8-L21

crs := func(ctx iris.Context) {
    ctx.Header("Access-Control-Allow-Origin", "*")
    ctx.Header("Access-Control-Allow-Credentials", "true")

    if ctx.Method() == iris.MethodOptions {
        ctx.Header("Access-Control-Methods", "POST, PUT, PATCH, DELETE")
        ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
        ctx.Header("Access-Control-Max-Age", "86400")
        ctx.StatusCode(iris.StatusNoContent)
        return
    }

    ctx.Next()
} 

However, you still need to call the AllowMethods(iris.MethodOptions) in the application/or party you want to register the cors: https://github.com/kataras/iris/blob/8359c9a0f5b0eadfc16ae24f879b477a18a8b9a4/_examples/experimental-handlers/cors/simple/main.go#L23

v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.

There is no other way to register this specific middleware because routes are registered per subdomain, method and path, so AllowMethods.

Don't forget that if you need to override the router behavior and register something before the iris router, you can also use the app.WrapRouter and put the cors code there (that way will not require AllowMethods).