Skip to content

Instantly share code, notes, and snippets.

@pinscript
Last active August 29, 2015 14:03
Show Gist options
  • Save pinscript/94580423363d3ec95fa8 to your computer and use it in GitHub Desktop.
Save pinscript/94580423363d3ec95fa8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
if c.Req.Method == "OPTIONS" {
fmt.Println("options")
c.Abort(200)
return
}
c.Next()
}
}
func main() {
r := gin.Default()
r.Use(CORSMiddleware())
r.GET("", func (g *gin.Context) {
g.JSON(200, gin.H{"foo":"bar"})
})
r.Run(":8082")
}
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Origin: *
Content-Type: application/json
Date: Thu, 03 Jul 2014 11:33:38 GMT
Content-Length: 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment