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
This commit is contained in:
Sergey Krashevich
2026-04-22 04:01:38 +03:00
parent ad2c09abf4
commit 812fa91d83
2 changed files with 10 additions and 0 deletions
+1
View File
@@ -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
+9
View File
@@ -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)
})
}