From 812fa91d83c460bd0941b5463c0fc684c1ae5e86 Mon Sep 17 00:00:00 2001 From: Sergey Krashevich Date: Wed, 22 Apr 2026 04:01:38 +0300 Subject: [PATCH] fix(api): improve CORS and preflight request handling - add support for handling OPTIONS method in middleware functions - ensure proper CORS headers are set for preflight requests --- README.md | 1 + internal/api/api.go | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/README.md b/README.md index 5d0172e9..04717805 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ Ultimate camera streaming application with support for dozens formats and protoc > - [#2130](https://github.com/AlexxIT/go2rtc/pull/2130) — HomeKit Secure Video > - [#2160](https://github.com/AlexxIT/go2rtc/pull/2160) — WebCodecs streaming support (@seydx) > - [#2174](https://github.com/AlexxIT/go2rtc/pull/2174) - Socket leaks in go2rtc - creality k2plus issue +> - [#2223](https://github.com/AlexxIT/go2rtc/pull/2223) — Fix CORS preflight requests support --- ## Screenshots diff --git a/internal/api/api.go b/internal/api/api.go index 13492573..5edf31f4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -224,6 +224,11 @@ func isLoopback(remoteAddr string) bool { func middlewareAuth(username, password string, localAuth bool, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "OPTIONS" { + next.ServeHTTP(w, r) + return + } + if localAuth || !isLoopback(r.RemoteAddr) { user, pass, ok := r.BasicAuth() if !ok || user != username || pass != password { @@ -242,6 +247,10 @@ func middlewareCORS(next http.Handler) http.Handler { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusNoContent) + return + } next.ServeHTTP(w, r) }) }