Comments (29)
I'm using smth like this right now.
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://domain.com")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
fmt.Println("OPTIONS")
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
r.Use(CORSMiddleware())
from gin.
@qwertmax - Super basic approach but works very well.
r.Use(func(c *gin.Context) {
// Run this on all requests
// Should be moved to a proper middleware
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,Token")
c.Next()
})
r.OPTIONS("/*cors", func(c *gin.Context) {
// Empty 200 response
})
from gin.
@alexandernyquist I am using the newest version of gin and I am on go1.3 darwin/amd64. (I just did go get -u . before sending this)
Also I have given you and @manucorporat read permissions to the repo. I think there may be too hard to get a runnable example without the rest of the app.
I think the only dependency the app has is Rethinkdb.
Routes: https://github.com/Lanciv/GoGradeAPI/blob/master/handlers/routes.go
Main: https://github.com/Lanciv/GoGradeAPI/blob/master/main.go
from gin.
What gin/go versions are you on? Can you please post a complete, runnable example? This[0] works fine for me.
[0] https://gist.github.com/alexandernyquist/94580423363d3ec95fa8
from gin.
Thanks for the access, however I only have access to a Windows machine at the moment.
I'll see if I can get a VirtualBox running this weekend.
from gin.
"http: multiple response.WriteHeader calls" will be fixed soon with this: #16
Anyway I think that message is just a warning, it guess it should work.
It's incredible that the standard library do not provide any way to know the current status code.
from gin.
@alexandernyquist I'll get a VM up for you real quick.
from gin.
@manucorporat Well I get a 404 and the headers aren't set at all :/
from gin.
Can you guys do a quick review of this: #24 ? once this is merged, your bug can be fixed easily.
from gin.
@manucorporat I switched to that commit but I am getting the same error.
from gin.
Of course! that commit do not fix it, but I need to merge that first :)
from gin.
@manucorporat Do you know when you will have it done?
from gin.
@alexandernyquist Would you still like me to get you a vm to test with?
from gin.
@alexandernyquist I just tested your gist and it is returning a 404 to OPTIONS.
from gin.
it will be fixed today!
from gin.
@MattAitchison Have you added route for OPTIONS? Unfortunately, there is no OPTIONS-method in the current master branch (PR coming).
Patching gin.go with a OPTIONS-method:
func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
group.Handle("OPTIONS", path, handlers)
}
And registering the route:
r.OPTIONS("", func (g *gin.Context) {
g.JSON(200, gin.H{"foo":"bar"})
})
Will work.
from gin.
@alexandernyquist Well I would like to handle OPTIONS inside my middleware. I don't believe I should have to mount the middleware and add a route for OPTIONS. I have added the following route which has fixed the problem for now. I hope it's only temporary.
r.Handle("OPTIONS", "/*cors", []gin.HandlerFunc{CORSMiddleware()})
It looks like the 404 handler sends a 404 before my OPTIONS middleware can write.
from gin.
Ah, I was a bit too quick there. I'll check it out when I get home.
from gin.
Just an update, this is already fixed in my local repo
from gin.
Can you guys try the develop branch? e1781e2
from gin.
@manucorporat that works like a charm. Nice!
from gin.
Works now! Thanks!
from gin.
has someone successful experience with cors?
from gin.
Hello I am getting multiple headers on 2 nd request.
from gin.
@shivkumarsingh7 can you describe a little bit more your problem?
from gin.
I am using middleware with below code
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://domain.com")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
fmt.Println("OPTIONS")
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
r.Use(CORSMiddleware())
It's working properly with package "github.com/gin-gonic/gin" but When I am changing package to "gopkg.in/gin-gonic/gin.v1" I am getting multiple headers on 2nd request.
from gin.
@shivkumarsingh7 may be because you receive 2 responses (OPTIONS and than GET/POST/whatever) ?
from gin.
@qwertmax apart from the option and one get, post, put or delete I am getting header twice in one response only
from gin.
Deal with http OPTIONS method currently:
engine := gin.Default() // return *gin.Engine
engine.Use(CorsMW) // incomplete
group := engine.Group("/prefix") // return *gin.RouterGroup
group.GET("/path", handlerFunc)
404 Happend:
engine := gin.Default()
engine := engine.Group("/prefix")
group.Use(CorsMW)
group.GET("/path", handlerFunc)
- Request will be processed by Engine's Middleware before matches the route config.
- Request will be processed by RouterGroup's Middleware after matches the route config.
So we use CorsMiddleware in *gin.Engine will process all CORS correctly.
from gin.
Related Issues (20)
- Attach Response Headers (or middlewares) to redirected requests (CORS issues) HOT 1
- Should context.GetRawData() also copy body to BodyBytesKey? HOT 3
- YAML BindBody should not parse JSON content HOT 1
- Gin do not support javascript ? HOT 5
- Does gin.Recovery() run before or after Group middleware? HOT 1
- How can i prevent a http connection to close HOT 3
- BasicAuth is not suitable for proxy auth
- Can't get status as expected from context.Status() HOT 1
- Gin Context implementation breaks context.Context contract HOT 4
- [Suggestions] Introducing an AI-powered robot to assist with daily issue and pull request (PR) tasks.
- Need c.JSON() response like behaviour for c.SSEvent() response for supporting first party clients like OpenAI SDK HOT 2
- custom time.Time type can not use bindQuery get a value. HOT 3
- configure server parameters HOT 1
- The binding:"required" tag does not seem to work for struct types HOT 3
- Is there a way to preserve order in JSON on response? HOT 1
- redirect is not success HOT 1
- I want to use shouldmindbodywith first and then use formafile, but it doesn't work right now HOT 3
- Extend the routing tree entry
- Transparent decompression for gzip, deflate, etc? HOT 1
- Custom time.Time type can not use bindQuery get a value 2 HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from gin.