@@ -424,24 +424,42 @@ func (s *Server) HandleSubdomain(middlewares ...func(http.Handler) http.Handler)
424424return
425425}
426426
427- //Use thepassed 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 therequest (possibly with the CORS middleware).
428+ mws := chi .Middlewares (append (middlewares ,s .determineCORSBehavior (token ,app )))
429429mws .Handler (http .HandlerFunc (func (rw http.ResponseWriter ,r * http.Request ) {
430430s .proxyWorkspaceApp (rw ,r ,* token ,r .URL .Path ,app )
431431})).ServeHTTP (rw ,r .WithContext (ctx ))
432432})
433433}
434434}
435435
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 {
437439return func (next http.Handler ) http.Handler {
440+ // Create the CORS middleware handler upfront.
441+ corsHandler := httpmw .WorkspaceAppCors (s .HostnameRegex ,app )(next )
442+
438443return http .HandlerFunc (func (rw http.ResponseWriter ,r * http.Request ) {
439444var behavior cors.AppCORSBehavior
440445if token != nil {
441446behavior = token .CORSBehavior
442447}
443448
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+ }
445463})
446464}
447465}