4 "git.jacobcasper.com/brackets/client"
5 "git.jacobcasper.com/brackets/db"
6 _ "github.com/mattn/go-sqlite3"
7 "github.com/zmb3/spotify"
12 type handler func(http.ResponseWriter, *http.Request)
15 lockedDb, err := db.New()
17 log.Fatal("Could not open db: ", err.Error())
20 client, err := client.Get()
22 log.Fatal("Could not get client: ", err.Error())
27 addArtistHandler(lockedDb, client),
30 log.Fatal(http.ListenAndServe(":8080", nil))
33 func addArtistHandler(db *db.DB, c *spotify.Client) handler {
34 return func(w http.ResponseWriter, r *http.Request) {
35 if r.Method != "POST" {
36 http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
41 artistId := r.PostForm.Get("artist_id")
44 http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
48 artist, err := c.GetArtist(spotify.ID(artistId))
50 log.Printf("Failed to retrieve artist %s: %s", artistId, err.Error())
51 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
57 db.Db.Exec("INSERT INTO ARTIST (ID, NAME) VALUES (?, ?)", artist.ID, artist.Name)
59 for _, genre := range artist.Genres {
60 result, err := db.Db.Exec("REPLACE INTO GENRE (NAME) VALUES (?)", genre)
62 log.Printf("Failed to insert genre %s: %s", genre, err.Error())
63 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
67 genreId, err := result.LastInsertId()
69 log.Print("Failed to retrieve last insert id: ", err.Error())
70 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
74 db.Db.Exec("INSERT INTO ARTIST_GENRE_XREF (ARTIST_ID, GENRE_ID) VALUES (?, ?)", artist.ID, genreId)
76 w.WriteHeader(http.StatusCreated)