From 056985799f7dcc1615a21dceef11878487a739d2 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Fri, 21 Oct 2022 04:24:07 +0400 Subject: [PATCH] Added Update() handler. A little reorganising in Entries(). --- internal/handlers/handlers.go | 51 +++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 5a1b910..13f35ff 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -33,9 +33,8 @@ func New(owner, password, anonymousName string, defaultPageSize int64, guestbook func (h *GuestbookHandlers) Entries(w http.ResponseWriter, r *http.Request) { var err error - var page_num int64 = 1 - var page_size int64 = h.defaultPageSize + var page_num int64 = 1 if r.URL.Query().Get("p") != "" { page_num, err = strconv.ParseInt(r.URL.Query().Get("p"), 10, 64) if err != nil { @@ -43,6 +42,7 @@ func (h *GuestbookHandlers) Entries(w http.ResponseWriter, r *http.Request) { } } + var page_size int64 = h.defaultPageSize if r.URL.Query().Get("ps") != "" { page_size, err = strconv.ParseInt(r.URL.Query().Get("ps"), 10, 64) if err != nil { @@ -179,6 +179,53 @@ func (h *GuestbookHandlers) Reply(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) } +func (h *GuestbookHandlers) Update(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Password") != h.password { + w.WriteHeader(http.StatusForbidden) + return + } + + entryID, err := strconv.ParseInt(server.GetURLParam(r, "entry"), 10, 64) + if err != nil { + http.Error(w, err.Error(), http.StatusUnprocessableEntity) + return + } + + if strings.HasSuffix(r.URL.Path, "reply") { + rp := guestbook.Reply{ID: entryID} + json.NewDecoder(r.Body).Decode(&rp) + + isCreated, err := h.db.UpdateReply(&rp) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + if isCreated { + w.WriteHeader(http.StatusCreated) + } + + w.Header().Add("Content-Type", "application/json") + json.NewEncoder(w).Encode(&rp) + } else { + et := guestbook.Entry{ID: entryID} + json.NewDecoder(r.Body).Decode(&et) + + isCreated, err := h.db.UpdateEntry(&et) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + if isCreated { + w.WriteHeader(http.StatusCreated) + } + + w.Header().Add("Content-Type", "application/json") + json.NewEncoder(w).Encode(&et) + } +} + func (h *GuestbookHandlers) Delete(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Password") != h.password { w.WriteHeader(http.StatusForbidden)