Created
August 11, 2019 05:34
-
-
Save dumindu/6493dead387d2c66359c3e7767806150 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (app *App) HandleUpdateBook(w http.ResponseWriter, r *http.Request) { | |
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64) | |
if err != nil || id == 0 { | |
app.logger.Info().Msgf("can not parse ID: %v", id) | |
w.WriteHeader(http.StatusUnprocessableEntity) | |
return | |
} | |
form := &model.BookForm{} | |
if err := json.NewDecoder(r.Body).Decode(form); err != nil { | |
app.logger.Warn().Err(err).Msg("") | |
w.WriteHeader(http.StatusUnprocessableEntity) | |
fmt.Fprintf(w, `{"error": "%v"}`, appErrFormDecodingFailure) | |
return | |
} | |
bookModel, err := form.ToModel() | |
if err != nil { | |
app.logger.Warn().Err(err).Msg("") | |
w.WriteHeader(http.StatusUnprocessableEntity) | |
fmt.Fprintf(w, `{"error": "%v"}`, appErrFormDecodingFailure) | |
return | |
} | |
bookModel.ID = uint(id) | |
if err := repository.UpdateBook(app.db, bookModel); err != nil { | |
if err == gorm.ErrRecordNotFound { | |
w.WriteHeader(http.StatusNotFound) | |
return | |
} | |
app.logger.Warn().Err(err).Msg("") | |
w.WriteHeader(http.StatusInternalServerError) | |
fmt.Fprintf(w, `{"error": "%v"}`, appErrDataUpdateFailure) | |
return | |
} | |
app.logger.Info().Msgf("Book updated: %d", id) | |
w.WriteHeader(http.StatusAccepted) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment