@@ -424,24 +424,42 @@ func (s *Server) HandleSubdomain(middlewares ...func(http.Handler) http.Handler)
424
424
return
425
425
}
426
426
427
- // Use the passed in app middlewares and CORS middleware with the token
428
- mws := chi .Middlewares (append (middlewares , s .injectCORSBehavior (token ), httpmw . WorkspaceAppCors ( s . HostnameRegex , app )))
427
+ // Proxy the request (possibly with the CORS middleware).
428
+ mws := chi .Middlewares (append (middlewares , s .determineCORSBehavior (token , app )))
429
429
mws .Handler (http .HandlerFunc (func (rw http.ResponseWriter , r * http.Request ) {
430
430
s .proxyWorkspaceApp (rw , r , * token , r .URL .Path , app )
431
431
})).ServeHTTP (rw , r .WithContext (ctx ))
432
432
})
433
433
}
434
434
}
435
435
436
- func (s * Server ) injectCORSBehavior (token * SignedToken ) func (http.Handler ) http.Handler {
436
+ // determineCORSBehavior examines the given token and conditionally applies
437
+ // CORS middleware if the token specifies that behavior.
438
+ func (s * Server ) determineCORSBehavior (token * SignedToken , app appurl.ApplicationURL ) func (http.Handler ) http.Handler {
437
439
return func (next http.Handler ) http.Handler {
440
+ // Create the CORS middleware handler upfront.
441
+ corsHandler := httpmw .WorkspaceAppCors (s .HostnameRegex , app )(next )
442
+
438
443
return http .HandlerFunc (func (rw http.ResponseWriter , r * http.Request ) {
439
444
var behavior cors.AppCORSBehavior
440
445
if token != nil {
441
446
behavior = token .CORSBehavior
442
447
}
443
448
444
- next .ServeHTTP (rw , r .WithContext (cors .WithBehavior (r .Context (), behavior )))
449
+ // Add behavior to context regardless of which handler we use,
450
+ // since we will use this later on to determine if we should strip
451
+ // CORS headers in the response.
452
+ r = r .WithContext (cors .WithBehavior (r .Context (), behavior ))
453
+
454
+ switch behavior {
455
+ case cors .AppCORSBehaviorPassthru :
456
+ // Bypass the CORS middleware.
457
+ next .ServeHTTP (rw , r )
458
+ return
459
+ default :
460
+ // Apply the CORS middleware.
461
+ corsHandler .ServeHTTP (rw , r )
462
+ }
445
463
})
446
464
}
447
465
}
0 commit comments