8
8
"fmt"
9
9
"net/http"
10
10
"strconv"
11
+ "strings"
11
12
12
13
"github.com/caddyserver/caddy/v2"
13
14
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
@@ -27,9 +28,10 @@ func init() {
27
28
28
29
// CorsOrigin implements an HTTP handler that generates a valid CORS Origin value
29
30
type CorsOrigin struct {
30
- AnyDomain bool `json:"any_domain,omitempty"`
31
- BaseDomain string `json:"base_domain,omitempty"`
32
- Debug bool `json:"debug,omitempty"`
31
+ AnyDomain bool `json:"any_domain,omitempty"`
32
+ BaseDomain string `json:"base_domain,omitempty"`
33
+ AllowedOrigins []string `json:"allowed_origins,omitempty"`
34
+ Debug bool `json:"debug,omitempty"`
33
35
}
34
36
35
37
// CaddyModule returns the Caddy module information.
@@ -54,9 +56,12 @@ func (m CorsOrigin) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddy
54
56
var allowedOrigins []string
55
57
if m .AnyDomain {
56
58
allowedOrigins = []string {"*" }
57
- } else {
59
+ } else if m . BaseDomain != "" {
58
60
allowedOrigins = []string {"*." + m .BaseDomain }
61
+ } else if len (m .AllowedOrigins ) != 0 {
62
+ allowedOrigins = m .AllowedOrigins
59
63
}
64
+
60
65
c := cors .New (cors.Options {
61
66
AllowedOrigins : allowedOrigins ,
62
67
AllowedMethods : allowedMethods ,
@@ -98,8 +103,15 @@ func (m *CorsOrigin) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
98
103
}
99
104
100
105
m .AnyDomain = b
106
+
101
107
case "base_domain" :
102
108
m .BaseDomain = value
109
+
110
+ case "allowed_origins" :
111
+ // comma separated
112
+ origins := strings .Split (value , "," )
113
+ m .AllowedOrigins = origins
114
+
103
115
case "debug" :
104
116
b , err := strconv .ParseBool (value )
105
117
if err != nil {
@@ -112,8 +124,12 @@ func (m *CorsOrigin) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
112
124
}
113
125
}
114
126
115
- if ! m .AnyDomain && m .BaseDomain == "" {
116
- return fmt .Errorf ("Please configure the base_domain subdirective" )
127
+ if m .BaseDomain != "" && len (m .AllowedOrigins ) != 0 {
128
+ return fmt .Errorf ("base_domain and allowed_origins subdirectives are mutually exclusive, configure only one of them" )
129
+ }
130
+
131
+ if ! m .AnyDomain && m .BaseDomain == "" && len (m .AllowedOrigins ) == 0 {
132
+ return fmt .Errorf ("Please configure the base_domain or allowed_origins subdirective" )
117
133
}
118
134
119
135
return nil
0 commit comments