-
Notifications
You must be signed in to change notification settings - Fork 1
/
cors.go
45 lines (38 loc) · 1.18 KB
/
cors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package middlewares
import (
"net/http"
"github.com/lovego/goa"
)
// crosss origin resource share
type CORS struct {
allow func(origin string, c *goa.Context) bool
SetHeader func(http.Header)
}
func NewCORS(allow func(origin string, c *goa.Context) bool) CORS {
return CORS{allow: allow}
}
func (cors CORS) Check(c *goa.Context) {
if c.Request.Header.Get(`Sec-Fetch-Site`) != "same-origin" {
if origin := c.Request.Header.Get(`Origin`); origin != `` && origin != c.Origin() {
if !cors.allow(origin, c) {
c.WriteHeader(http.StatusForbidden)
c.Write([]byte(`origin not allowed.`))
return
}
header := c.ResponseWriter.Header()
header.Set(`Access-Control-Allow-Origin`, origin)
header.Set(`Access-Control-Allow-Credentials`, `true`)
header.Set(`Vary`, `Accept-Encoding, Origin`)
if c.Request.Method == `OPTIONS` { // preflight request
header.Set(`Access-Control-Max-Age`, `86400`)
header.Set(`Access-Control-Allow-Methods`, `GET, POST, PUT, DELETE, PATCH`)
header.Set(`Access-Control-Allow-Headers`, `X-Requested-With, Content-Type, withCredentials`)
if cors.SetHeader != nil {
cors.SetHeader(header)
}
return
}
}
}
c.Next()
}