forked from krakend/krakend-cors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors.go
74 lines (62 loc) · 1.63 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
63
64
65
66
67
68
69
70
71
72
73
74
package cors
import (
"time"
"github.com/luraproject/lura/v2/config"
)
// Namespace is the key to look for extra configuration details
const Namespace = "github_com/devopsfaith/krakend-cors"
// Config holds the configuration of CORS
type Config struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge time.Duration
Debug bool
}
// ConfigGetter implements the config.ConfigGetter interface. It parses the extra config an allowed
// origin must be defined, the rest of the options will use a default if not defined.
func ConfigGetter(e config.ExtraConfig) interface{} {
v, ok := e[Namespace]
if !ok {
return nil
}
tmp, ok := v.(map[string]interface{})
if !ok {
return nil
}
cfg := Config{}
cfg.AllowOrigins = getList(tmp, "allow_origins")
cfg.AllowMethods = getList(tmp, "allow_methods")
cfg.AllowHeaders = getList(tmp, "allow_headers")
cfg.ExposeHeaders = getList(tmp, "expose_headers")
if allowCredentials, ok := tmp["allow_credentials"]; ok {
if v, ok := allowCredentials.(bool); ok {
cfg.AllowCredentials = v
}
}
if debug, ok := tmp["debug"]; ok {
v, ok := debug.(bool)
cfg.Debug = ok && v
}
if maxAge, ok := tmp["max_age"]; ok {
if d, err := time.ParseDuration(maxAge.(string)); err == nil {
cfg.MaxAge = d
}
}
return cfg
}
func getList(data map[string]interface{}, name string) []string {
out := []string{}
if vs, ok := data[name]; ok {
if v, ok := vs.([]interface{}); ok {
for _, s := range v {
if j, ok := s.(string); ok {
out = append(out, j)
}
}
}
}
return out
}