@@ -50,6 +50,31 @@ func setNoCacheHeaders(w http.ResponseWriter) {
5050 w .Header ().Set ("Expires" , "0" )
5151}
5252
53+ func setCORSHeaders (w http.ResponseWriter , r * http.Request ) bool {
54+ corsOriginsStr := os .Getenv ("TSUNAMI_CORS" )
55+ if corsOriginsStr == "" {
56+ return false
57+ }
58+
59+ origin := r .Header .Get ("Origin" )
60+ if origin == "" {
61+ return false
62+ }
63+
64+ allowedOrigins := strings .Split (corsOriginsStr , "," )
65+ for _ , allowedOrigin := range allowedOrigins {
66+ allowedOrigin = strings .TrimSpace (allowedOrigin )
67+ if allowedOrigin == origin {
68+ w .Header ().Set ("Access-Control-Allow-Origin" , origin )
69+ w .Header ().Set ("Access-Control-Allow-Methods" , "GET, POST, OPTIONS" )
70+ w .Header ().Set ("Access-Control-Allow-Headers" , "Content-Type" )
71+ w .Header ().Set ("Access-Control-Allow-Credentials" , "true" )
72+ return true
73+ }
74+ }
75+ return false
76+ }
77+
5378func (h * httpHandlers ) registerHandlers (mux * http.ServeMux , opts handlerOpts ) {
5479 mux .HandleFunc ("/api/render" , h .handleRender )
5580 mux .HandleFunc ("/api/updates" , h .handleSSE )
@@ -200,8 +225,14 @@ func (h *httpHandlers) handleData(w http.ResponseWriter, r *http.Request) {
200225 }
201226 }()
202227
228+ setCORSHeaders (w , r )
203229 setNoCacheHeaders (w )
204230
231+ if r .Method == http .MethodOptions {
232+ w .WriteHeader (http .StatusOK )
233+ return
234+ }
235+
205236 if r .Method != http .MethodGet {
206237 http .Error (w , "method not allowed" , http .StatusMethodNotAllowed )
207238 return
@@ -224,8 +255,14 @@ func (h *httpHandlers) handleConfig(w http.ResponseWriter, r *http.Request) {
224255 }
225256 }()
226257
258+ setCORSHeaders (w , r )
227259 setNoCacheHeaders (w )
228260
261+ if r .Method == http .MethodOptions {
262+ w .WriteHeader (http .StatusOK )
263+ return
264+ }
265+
229266 switch r .Method {
230267 case http .MethodGet :
231268 h .handleConfigGet (w , r )
@@ -293,8 +330,14 @@ func (h *httpHandlers) handleSchemas(w http.ResponseWriter, r *http.Request) {
293330 }
294331 }()
295332
333+ setCORSHeaders (w , r )
296334 setNoCacheHeaders (w )
297335
336+ if r .Method == http .MethodOptions {
337+ w .WriteHeader (http .StatusOK )
338+ return
339+ }
340+
298341 if r .Method != http .MethodGet {
299342 http .Error (w , "method not allowed" , http .StatusMethodNotAllowed )
300343 return
@@ -506,8 +549,14 @@ func (h *httpHandlers) handleManifest(manifestFileBytes []byte) http.HandlerFunc
506549 }
507550 }()
508551
552+ setCORSHeaders (w , r )
509553 setNoCacheHeaders (w )
510554
555+ if r .Method == http .MethodOptions {
556+ w .WriteHeader (http .StatusOK )
557+ return
558+ }
559+
511560 if r .Method != http .MethodGet {
512561 http .Error (w , "method not allowed" , http .StatusMethodNotAllowed )
513562 return
0 commit comments