Exemple #1
0
// Create a new album.
func PostAlbums(w http.ResponseWriter, r *http.Request) {
	// retrieve route parameters
	env := GetRequestEnv(r)

	// decode the album body
	var album models.Album
	if err := json.NewDecoder(r.Body).Decode(&album); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// retrieve album songs so we don't overwrite their fields when
	// we create the album
	for i, _ := range album.Songs {
		song := &album.Songs[i]
		if err := env.DB.Find(&song).Error; err != nil {
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		}
	}

	// create the album
	album.ID = 0
	if err := env.DB.Create(&album).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(album); err != nil {
		log.Fatal(err)
	}
}
Exemple #2
0
// Update an album.
func PutAlbum(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 album
	var album models.Album
	if err := env.DB.Find(&album, id).Error; err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	// decode the album body
	if err := json.NewDecoder(r.Body).Decode(&album); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// retrieve album songs so we don't overwrite their fields when
	// we update the album
	for i, _ := range album.Songs {
		song := &album.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 album
	tx := env.DB.Begin()

	// update the album songs
	if err := tx.Model(&album).Association("Songs").Replace(album.Songs).Error; err != nil {
		tx.Rollback()
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// save the updated album using the original primary key
	album.ID = id
	if err := tx.Save(&album).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(album); err != nil {
		log.Fatal(err)
	}
}