From 7599daf34a97a72ef14faa42b1b9f0b85beb0cf4 Mon Sep 17 00:00:00 2001 From: Sergey Parshukov Date: Wed, 31 Jul 2019 00:11:26 +0300 Subject: [PATCH 1/2] Correct HTTP responses and semantic codes --- messenger.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/messenger.go b/messenger.go index 8629c01..1177093 100644 --- a/messenger.go +++ b/messenger.go @@ -280,25 +280,37 @@ func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) { err := json.Unmarshal(body, &rec) if err != nil { fmt.Println("could not decode response:", err) - fmt.Fprintln(w, `{status: 'not ok'}`) + respond(w, http.StatusBadRequest) return } if rec.Object != "page" { fmt.Println("Object is not page, undefined behaviour. Got", rec.Object) + respond(w, http.StatusUnprocessableEntity) + return } if m.verify { if err := m.checkIntegrity(r); err != nil { fmt.Println("could not verify request:", err) - fmt.Fprintln(w, `{status: 'not ok'}`) + respond(w, http.StatusUnauthorized) return } } m.dispatch(rec) - fmt.Fprintln(w, `{status: 'ok'}`) + respond(w, http.StatusAccepted) // We do not return any meaningful response immediately so it should be 202 +} + +func respond(w http.ResponseWriter, code int) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + if code < 400 { + fmt.Fprintln(w, `{"status": "ok"}`) + } else { + fmt.Fprintln(w, `{"status": "not ok"}`) + } } // checkIntegrity checks the integrity of the requests received From f404f6afa4cf36de4ffde4b576a46263185c55a7 Mon Sep 17 00:00:00 2001 From: Sergey Parshukov Date: Wed, 31 Jul 2019 00:43:42 +0300 Subject: [PATCH 2/2] Put back mandatory 200 OK --- messenger.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/messenger.go b/messenger.go index 1177093..1d2b0fe 100644 --- a/messenger.go +++ b/messenger.go @@ -305,12 +305,7 @@ func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) { func respond(w http.ResponseWriter, code int) { w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - if code < 400 { - fmt.Fprintln(w, `{"status": "ok"}`) - } else { - fmt.Fprintln(w, `{"status": "not ok"}`) - } + fmt.Fprintf(w, `{"code": %d, "status": "%s"}`, code, http.StatusText(code)) } // checkIntegrity checks the integrity of the requests received