1
0
Fork 0

Added Update() handler. A little reorganising in Entries().

This commit is contained in:
Alexander Andreev 2022-10-21 04:24:07 +04:00
parent 57879522a1
commit 056985799f
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F
1 changed files with 49 additions and 2 deletions

View File

@ -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)