widness
2/15/2018 - 3:47 PM

update function

http://localhost:8000/api/books/2

//Headers
Key: Content-Type
Value: application/json

//Body -> raw

{
	"id": "2",
	"isbn": "7777777",
	"title": "Updated Title",
	"author": {
		"firstname": "Jeff", 
		"lastname": "Thompson"
	}
}
func updateBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			var book Book
			_ = json.NewDecoder(r.Body).Decode(&book)
			book.ID = params["id"] // Mock ID - not safe
			books = append(books, book)
			json.NewEncoder(w).Encode(book)
			return
		}
	}
	json.NewEncoder(w).Encode(books)
}