Skip to content

Commit e97d61d

Browse files
committed
added CORS headers
1 parent f91c008 commit e97d61d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

main.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ const (
2727

2828
func main() {
2929

30+
// gin.SetMode(gin.ReleaseMode)
31+
3032
jsondb, err := db.OpenDB(dbname)
3133
if err != nil {
3234
fmt.Println(err)
@@ -48,6 +50,8 @@ func main() {
4850
json.Unmarshal(read, &conf)
4951

5052
r := gin.Default()
53+
54+
r.Use(CORSMiddleware())
5155
r.GET("/", Get)
5256
r.GET("/:id", GetOne)
5357
r.POST("/", Create)
@@ -60,6 +64,26 @@ func main() {
6064
r.Run(":" + conf["port"].(string))
6165
}
6266

67+
// CORSMiddleware function for injecting CORS headers
68+
// allows requests from any origin with caching for 1 day
69+
func CORSMiddleware() gin.HandlerFunc {
70+
return func(c *gin.Context) {
71+
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
72+
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
73+
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE, UPDATE")
74+
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
75+
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
76+
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
77+
78+
if c.Request.Method == "OPTIONS" {
79+
fmt.Println("OPTIONS")
80+
c.AbortWithStatus(200)
81+
} else {
82+
c.Next()
83+
}
84+
}
85+
}
86+
6387
// BulkDelete deletes record by id
6488
func BulkDelete(c *gin.Context) {
6589

0 commit comments

Comments
 (0)