-
Notifications
You must be signed in to change notification settings - Fork 344
/
cors.go
62 lines (52 loc) · 1.36 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cors
import (
"github.com/zalando/skipper/filters"
)
const (
name = "corsOrigin"
allowOriginHeader = "Access-Control-Allow-Origin"
)
type basicSpec struct {
}
type filter struct {
allowedOrigins []string
}
// NewOrigin creates a CORS origin handler
// that can check for allowed origin or set an all allowed header
func NewOrigin() filters.Spec {
return &basicSpec{}
}
// Response checks for the origin header if there are allowed origins
// otherwise it just sets '*' as the value
func (a filter) Response(ctx filters.FilterContext) {
if len(a.allowedOrigins) == 0 {
ctx.Response().Header.Set(allowOriginHeader, "*")
return
}
origin := ctx.Request().Header.Get("Origin")
if origin == "" {
return
}
for _, o := range a.allowedOrigins {
if o == origin {
ctx.Response().Header.Set(allowOriginHeader, o)
return
}
}
}
// Request is a noop
func (a filter) Request(filters.FilterContext) {}
// CreateFilter takes an optional string array.
// If any argument is not a string, it will return an error
func (spec basicSpec) CreateFilter(args []interface{}) (filters.Filter, error) {
f := &filter{}
for _, a := range args {
if s, ok := a.(string); ok {
f.allowedOrigins = append(f.allowedOrigins, s)
} else {
return nil, filters.ErrInvalidFilterParameters
}
}
return f, nil
}
func (spec basicSpec) Name() string { return name }