From 852c820e2b6eac06f5f094d14f4d1310971037dd Mon Sep 17 00:00:00 2001 From: Gabriel Belinsky Date: Thu, 21 Sep 2023 13:00:45 -0700 Subject: [PATCH] Added chunk handler --- internal/apiServer/apiServer.go | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/internal/apiServer/apiServer.go b/internal/apiServer/apiServer.go index e36b716..f4ffd46 100644 --- a/internal/apiServer/apiServer.go +++ b/internal/apiServer/apiServer.go @@ -19,6 +19,49 @@ type ApiServer struct { Metadata *metadata.MetadataServer } +func (apiServer *ApiServer) chunkHandler(w http.ResponseWriter, r *http.Request) { + + // chunkIndex starts at 0 + chunkIndexString := r.URL.Query().Get("chunkindex") + chunkSizeString := r.URL.Query().Get("chunksize") + + chunkIndex := 0 + var err error + if chunkIndexString != "" { + chunkIndex, err = strconv.Atoi(chunkIndexString) + } + if err != nil { + http.Error(w, fmt.Sprint(err), http.StatusBadRequest) + } + + chunkSize := 0 + if chunkSizeString != "" { + chunkSize, err = strconv.Atoi(chunkSizeString) + } + if err != nil { + http.Error(w, fmt.Sprint(err), http.StatusBadRequest) + } + + filename := path.Base(path.Dir(r.URL.Path)) + + contents, err := apiServer.Audio.Download(filename) + if err != nil { + http.Error(w, fmt.Sprint(err), http.StatusNotFound) + return + } + + startIndex := chunkIndex * chunkSize + if startIndex > len(contents) { + http.Error(w, "index out of bounds", http.StatusBadRequest) + } + endIndex := startIndex + chunkSize + if endIndex > len(contents) { + endIndex = len(contents) + } + + w.Write(contents[startIndex:endIndex]) + +} func (apiServer *ApiServer) filesHandler(w http.ResponseWriter, r *http.Request) { filename := path.Base(r.URL.Path) @@ -99,6 +142,8 @@ func (apiServer *ApiServer) Serve() { r.Get("/files/{filename}", apiServer.filesHandler) r.Post("/files/{filename}", apiServer.filesHandler) r.Get("/files/{filename}/metadata", apiServer.metadataHandler) + // chunkNumber + r.Get("/files/{filename}/chunk", apiServer.chunkHandler) log.Fatal(http.ListenAndServe(":3030", r)) }