package apiServer import ( "encoding/json" "fmt" "io" "log" "net/http" "path" "strconv" "dread.land/deepgram-demo/internal/audio" "dread.land/deepgram-demo/internal/metadata" ) type ApiServer struct { Audio *audio.AudioServer Metadata *metadata.MetadataServer } func (apiServer *ApiServer) filesHandler(w http.ResponseWriter, r *http.Request) { filename := path.Base(r.URL.Path) switch r.Method { case "GET": // get file contents, err := apiServer.Audio.Download(filename) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusNotFound) return } w.Write(contents) return case "POST": // save file contents, err := io.ReadAll(r.Body) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } err = apiServer.Audio.Upload(filename, contents) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusConflict) } return default: // error unsupported http.Error(w, "unsupported", http.StatusMethodNotAllowed) return } } func (apiServer *ApiServer) metadataHandler(w http.ResponseWriter, r *http.Request) { filename := path.Base(r.URL.Path) switch r.Method { case "GET": // get metadata meta, err := apiServer.Metadata.Info(filename) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusNotFound) return } response, err := json.Marshal(meta) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } fmt.Fprint(w, string(response)) return default: http.Error(w, "unsupported", http.StatusMethodNotAllowed) return } } func (apiServer *ApiServer) listHandler(w http.ResponseWriter, r *http.Request) { maxdurationString := r.URL.Query().Get("maxduration") maxduration := 0 var err error if maxdurationString != "" { maxduration, err = strconv.Atoi(maxdurationString) } if err != nil { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return // error Bad Request } list := apiServer.Metadata.List(maxduration) response, err := json.Marshal(list) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } fmt.Fprint(w, string(response)) } func (apiServer *ApiServer) Serve() { // POST and GET media http.HandleFunc("/files/", apiServer.filesHandler) // list media http.HandleFunc("/files", apiServer.listHandler) // list metadata (with filter) http.HandleFunc("/metadata", apiServer.listHandler) // GET metadata http.HandleFunc("/metadata/", apiServer.metadataHandler) log.Fatal(http.ListenAndServe(":3030", nil)) }