Пример #1
0
// Create a new song.
func PostSongs(w http.ResponseWriter, r *http.Request) {
	// retrieve route parameters
	env := GetRequestEnv(r)

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

	// create the song
	song.ID = 0
	if err := env.DB.Create(&song).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(song); err != nil {
		log.Fatal(err)
	}
}
Пример #2
0
// Update a song.
func PutSong(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 song
	var song models.Song
	if err := env.DB.Find(&song, id).Error; err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

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

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