@@ -147,13 +147,25 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
147
147
config .AllowMethods = DefaultCORSConfig .AllowMethods
148
148
}
149
149
150
- allowOriginPatterns := [] string {}
150
+ allowOriginPatterns := make ([] * regexp. Regexp , 0 , len ( config . AllowOrigins ))
151
151
for _ , origin := range config .AllowOrigins {
152
+ if origin == "*" {
153
+ continue // "*" is handled differently and does not need regexp
154
+ }
152
155
pattern := regexp .QuoteMeta (origin )
153
156
pattern = strings .ReplaceAll (pattern , "\\ *" , ".*" )
154
157
pattern = strings .ReplaceAll (pattern , "\\ ?" , "." )
155
158
pattern = "^" + pattern + "$"
156
- allowOriginPatterns = append (allowOriginPatterns , pattern )
159
+
160
+ re , err := regexp .Compile (pattern )
161
+ if err != nil {
162
+ // this is to preserve previous behaviour - invalid patterns were just ignored.
163
+ // If we would turn this to panic, users with invalid patterns
164
+ // would have applications crashing in production due unrecovered panic.
165
+ // TODO: this should be turned to error/panic in `v5`
166
+ continue
167
+ }
168
+ allowOriginPatterns = append (allowOriginPatterns , re )
157
169
}
158
170
159
171
allowMethods := strings .Join (config .AllowMethods , "," )
@@ -239,7 +251,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
239
251
}
240
252
if checkPatterns {
241
253
for _ , re := range allowOriginPatterns {
242
- if match , _ := regexp .MatchString (re , origin ); match {
254
+ if match := re .MatchString (origin ); match {
243
255
allowOrigin = origin
244
256
break
245
257
}
0 commit comments