// Create a new artist. func PostArtists(w http.ResponseWriter, r *http.Request) { // retrieve route parameters env := GetRequestEnv(r) // decode the artist body var artist models.Artist if err := json.NewDecoder(r.Body).Decode(&artist); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // retrieve artist songs so we don't overwrite their fields when // we create the artist for i, _ := range artist.Songs { song := &artist.Songs[i] if err := env.DB.Find(&song).Error; err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } } // create the artist artist.ID = 0 if err := env.DB.Create(&artist).Error; err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // encode the response w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(artist); err != nil { log.Fatal(err) } }
// Update an artist. func PutArtist(w http.ResponseWriter, r *http.Request) { // retrieve route parameters env := GetRequestEnv(r) vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // retrieve the artist var artist models.Artist if err := env.DB.Find(&artist, id).Error; err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } // decode the artist body if err := json.NewDecoder(r.Body).Decode(&artist); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // retrieve artist songs so we don't overwrite their fields when // we update the artist for i, _ := range artist.Songs { song := &artist.Songs[i] if err := env.DB.Find(&song).Error; err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } } // start a transaction for updating the artist tx := env.DB.Begin() // update the artist songs if err := tx.Model(&artist).Association("Songs").Replace(artist.Songs).Error; err != nil { tx.Rollback() http.Error(w, err.Error(), http.StatusInternalServerError) return } // save the updated artist using the original primary key artist.ID = id if err := tx.Save(&artist).Error; err != nil { tx.Rollback() http.Error(w, err.Error(), http.StatusInternalServerError) return } // commit the transaction if err := tx.Commit().Error; err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // encode the response w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(artist); err != nil { log.Fatal(err) } }