@@ -27,6 +27,8 @@ const (
27
27
28
28
func main () {
29
29
30
+ // gin.SetMode(gin.ReleaseMode)
31
+
30
32
jsondb , err := db .OpenDB (dbname )
31
33
if err != nil {
32
34
fmt .Println (err )
@@ -48,6 +50,8 @@ func main() {
48
50
json .Unmarshal (read , & conf )
49
51
50
52
r := gin .Default ()
53
+
54
+ r .Use (CORSMiddleware ())
51
55
r .GET ("/" , Get )
52
56
r .GET ("/:id" , GetOne )
53
57
r .POST ("/" , Create )
@@ -60,6 +64,26 @@ func main() {
60
64
r .Run (":" + conf ["port" ].(string ))
61
65
}
62
66
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
+
63
87
// BulkDelete deletes record by id
64
88
func BulkDelete (c * gin.Context ) {
65
89
0 commit comments