cors icon indicating copy to clipboard operation
cors copied to clipboard

Cannot use cors default as type gin.HandlerFunc in argument to router.Use

Open emmanuelbenson opened this issue 7 years ago • 5 comments

How do one use this package with gin-gonic?

I have this error: cannot use cors.Default() (type *cors.Cors) as type gin.HandlerFunc in argument to r.Use. My snippet below:

r := gin.Default() r.Use(cors.Default()) v1 := r.Group("/v1") { item := v1.Group("/item") { item.POST("/new", controllers.AddItem) item.GET("/", controllers.GetAllItems) item.GET("/:id", controllers.GetItem) item.PUT("/update", controllers.UpdateItem) item.DELETE("/", controllers.DeleteItem) } verify := v1.Group("/verify") { verify.POST("/", controllers.VerifyItem) } } return r

emmanuelbenson avatar Oct 20 '18 15:10 emmanuelbenson

did you import cors "github.com/rs/cors/wrapper/gin" ? Also, would really help if you put the snippet with markdown code...

RCM7 avatar Oct 21 '18 15:10 RCM7

did you import cors "github.com/rs/cors/wrapper/gin" ? Also, would really help if you put the snippet with markdown code...

Yes I did.

r := gin.Default()
r.Use(cors.Default())
v1 := r.Group("/v1")
{
item := v1.Group("/item")
{
item.POST("/new", controllers.AddItem)
item.GET("/", controllers.GetAllItems)
item.GET("/:id", controllers.GetItem)
item.PUT("/update", controllers.UpdateItem)
item.DELETE("/", controllers.DeleteItem)
}
verify := v1.Group("/verify")
{
verify.POST("/", controllers.VerifyItem)
}
}
return r

emmanuelbenson avatar Oct 23 '18 07:10 emmanuelbenson

Please include the imports you are using in your snippet.

rs avatar May 23 '19 20:05 rs

@emmanuelbenson did you try putting:

r.Use(cors.Default())

to the last (before return):

r.Use(cors.Default())
return r

This is likely due to no OPTIONS routes defined for the router, gin will just return 404. But if we put the cors into the bottom (i.e. the last one in the router middleware stack), it will catch all unhandled request (and generate a cors response).

bcho avatar May 25 '19 04:05 bcho

The error is -

cannot use "github.com/rs/cors/wrapper/gin".AllowAll() (type "github.com/gin-gonic/gin".HandlerFunc) as type "github.com/<your workspace>/vendor/github.com/gin-gonic/gin".HandlerFunc in argument to router.Use

This is due to your dependencies not being updated

go get -u github.com/rs/cors/wrapper/gin
godep save

and this should fix the above issue

gondar00 avatar Jul 23 '19 09:07 gondar00

@rs This issue could likely be closed.

jub0bs avatar Sep 10 '23 08:09 jub0bs