Giter VIP home page Giter VIP logo

Comments (29)

qwertmax avatar qwertmax commented on April 24, 2024 30

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.

nazwa avatar nazwa commented on April 24, 2024 2

@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.

mattatcha avatar mattatcha commented on April 24, 2024 1

@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.

pinscript avatar pinscript commented on April 24, 2024

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.

pinscript avatar pinscript commented on April 24, 2024

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.

manucorporat avatar manucorporat commented on April 24, 2024

"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.

mattatcha avatar mattatcha commented on April 24, 2024

@alexandernyquist I'll get a VM up for you real quick.

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

@manucorporat Well I get a 404 and the headers aren't set at all :/

from gin.

manucorporat avatar manucorporat commented on April 24, 2024

Can you guys do a quick review of this: #24 ? once this is merged, your bug can be fixed easily.

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

@manucorporat I switched to that commit but I am getting the same error.

from gin.

manucorporat avatar manucorporat commented on April 24, 2024

Of course! that commit do not fix it, but I need to merge that first :)

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

@manucorporat Do you know when you will have it done?

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

@alexandernyquist Would you still like me to get you a vm to test with?

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

@alexandernyquist I just tested your gist and it is returning a 404 to OPTIONS.

from gin.

manucorporat avatar manucorporat commented on April 24, 2024

it will be fixed today!

from gin.

pinscript avatar pinscript commented on April 24, 2024

@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.

mattatcha avatar mattatcha commented on April 24, 2024

@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.

pinscript avatar pinscript commented on April 24, 2024

Ah, I was a bit too quick there. I'll check it out when I get home.

from gin.

manucorporat avatar manucorporat commented on April 24, 2024

Just an update, this is already fixed in my local repo

from gin.

manucorporat avatar manucorporat commented on April 24, 2024

Can you guys try the develop branch? e1781e2

from gin.

pinscript avatar pinscript commented on April 24, 2024

@manucorporat that works like a charm. Nice!

from gin.

mattatcha avatar mattatcha commented on April 24, 2024

Works now! Thanks!

from gin.

qwertmax avatar qwertmax commented on April 24, 2024

has someone successful experience with cors?

from gin.

shivkumarsingh7 avatar shivkumarsingh7 commented on April 24, 2024

Hello I am getting multiple headers on 2 nd request.
screen shot 2018-08-17 at 4 43 18 pm

from gin.

qwertmax avatar qwertmax commented on April 24, 2024

@shivkumarsingh7 can you describe a little bit more your problem?

from gin.

shivkumarsingh7 avatar shivkumarsingh7 commented on April 24, 2024

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.

qwertmax avatar qwertmax commented on April 24, 2024

@shivkumarsingh7 may be because you receive 2 responses (OPTIONS and than GET/POST/whatever) ?

from gin.

shivkumarsingh7 avatar shivkumarsingh7 commented on April 24, 2024

@qwertmax apart from the option and one get, post, put or delete I am getting header twice in one response only

from gin.

g10guang avatar g10guang commented on April 24, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.