From 2e3a612065854639ed3624f056b524c21eeb4a0c Mon Sep 17 00:00:00 2001 From: robrotheram Date: Sun, 25 Feb 2024 12:58:24 +0000 Subject: [PATCH] added proxy cache --- pkg/api/handlers.go | 35 +++++++++++-------- .../app/components/player/VideoPlayer.jsx | 2 +- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/pkg/api/handlers.go b/pkg/api/handlers.go index 9b33602..7fe7c5e 100644 --- a/pkg/api/handlers.go +++ b/pkg/api/handlers.go @@ -411,28 +411,35 @@ func (h *handler) handleMediaProxy(w http.ResponseWriter, r *http.Request) { http.Error(w, "URL parameter is missing", http.StatusBadRequest) return } - // Make an HTTP request to the provided URL - resp, err := http.Get(media.GetAudioUrl()) + // Create a new request to the destination URL + req, err := http.NewRequest(r.Method, media.GetAudioUrl(), r.Body) if err != nil { - http.Error(w, fmt.Sprintf("Failed to fetch URL: %s", err), http.StatusInternalServerError) + http.Error(w, fmt.Sprintf("Failed to create request: %s", err), http.StatusInternalServerError) return } - defer resp.Body.Close() + req.Header = r.Header - // Forward the response from the external URL back to the client - body, err := io.ReadAll(resp.Body) + // Perform the request + client := &http.Client{} + resp, err := client.Do(req) if err != nil { - http.Error(w, fmt.Sprintf("Failed to read response body: %s", err), http.StatusInternalServerError) + http.Error(w, fmt.Sprintf("Failed to perform request: %s", err), http.StatusInternalServerError) return } + defer resp.Body.Close() - // Set the content type based on the response header - contentType := resp.Header.Get("Content-Type") - if contentType != "" { - w.Header().Set("Content-Type", contentType) + // Copy headers from the response + for key, values := range resp.Header { + for _, value := range values { + w.Header().Add(key, value) + } } - - // Write the response body back to the client w.WriteHeader(resp.StatusCode) - w.Write(body) + + // Stream the response body to the client + _, err = io.Copy(w, resp.Body) + if err != nil { + fmt.Printf("Failed to stream response body: %s\n", err) + return + } } diff --git a/ui/src/pages/app/components/player/VideoPlayer.jsx b/ui/src/pages/app/components/player/VideoPlayer.jsx index f38e54c..55765ac 100644 --- a/ui/src/pages/app/components/player/VideoPlayer.jsx +++ b/ui/src/pages/app/components/player/VideoPlayer.jsx @@ -115,7 +115,7 @@ export const VideoPlayer = ({ state, connection }) => { const getMediaUrl = () => { switch(state.current.type){ case "YOUTUBE_LIVE": return state.current.url - case "YOUTUBE": return `/api/channel/${getRoomId()}/proxy` + case "YOUTUBE": return `/api/channel/${getRoomId()}/proxy?id=${state.current.id}` default: return state.current.audio_url } }