Skip to content

Commit

Permalink
added CORS headers
Browse files Browse the repository at this point in the history
  • Loading branch information
vsrc committed Oct 23, 2017
1 parent f91c008 commit e97d61d
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const (

func main() {

// gin.SetMode(gin.ReleaseMode)

jsondb, err := db.OpenDB(dbname)
if err != nil {
fmt.Println(err)
Expand All @@ -48,6 +50,8 @@ func main() {
json.Unmarshal(read, &conf)

r := gin.Default()

r.Use(CORSMiddleware())
r.GET("/", Get)
r.GET("/:id", GetOne)
r.POST("/", Create)
Expand All @@ -60,6 +64,26 @@ func main() {
r.Run(":" + conf["port"].(string))
}

// CORSMiddleware function for injecting CORS headers
// allows requests from any origin with caching for 1 day
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, 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()
}
}
}

// BulkDelete deletes record by id
func BulkDelete(c *gin.Context) {

Expand Down

0 comments on commit e97d61d

Please sign in to comment.