From: Jacob Casper Date: Thu, 16 Apr 2020 22:19:38 +0000 (-0500) Subject: Add artist lookup by genre X-Git-Url: https://git.jacobcasper.com/?a=commitdiff_plain;h=eac0dfd66703dffd39c925fdba612f8aceb7b510;p=brackets.git Add artist lookup by genre --- diff --git a/main.go b/main.go index 81803f7..b59a627 100644 --- a/main.go +++ b/main.go @@ -15,15 +15,9 @@ func main() { log.Fatal("Could not set up Env: ", err.Error()) } - http.HandleFunc( - "/artist/", - artist.Index(env), - ) - - http.HandleFunc( - "/artist/add", - artist.Add(env), - ) + http.HandleFunc("/artist/", artist.Index(env)) + http.HandleFunc("/artist/genre", artist.ByGenre(env)) + http.HandleFunc("/artist/add", artist.Add(env)) http.HandleFunc("/genre", genre.Index(env)) diff --git a/routes/artist/artist.go b/routes/artist/artist.go index 09788ad..e6eb320 100644 --- a/routes/artist/artist.go +++ b/routes/artist/artist.go @@ -114,3 +114,46 @@ func Add(env *env.Env) routes.Handler { w.WriteHeader(http.StatusCreated) } } + +func ByGenre(env *env.Env) routes.Handler { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return + } + + w.Header().Set("Content-Type", "application/json") + genreName := r.FormValue("genre_name") + if genreName != "" { + rows, err := env.Db.Db.Query("SELECT ID, NAME FROM ARTIST WHERE ID IN (SELECT ARTIST_ID FROM ARTIST_GENRE_XREF WHERE GENRE_ID IN (SELECT ID FROM GENRE WHERE NAME = lower(?))) LIMIT 20", genreName) + if err != nil { + log.Print(err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + defer rows.Close() + + artists := make([]types.Artist, 0) + for rows.Next() { + artist := types.Artist{} + if err := rows.Scan(&artist.ID, &artist.Name); err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + artists = append(artists, artist) + } + if err = rows.Err(); err != nil { + log.Print(err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + b, err := json.Marshal(artists) + if err != nil { + log.Print(err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + w.Write(b) + } + } +}