From efdae319feb50bcda8c7481abd854680ada43f3a Mon Sep 17 00:00:00 2001 From: Stephen McQuay Date: Sat, 28 Dec 2013 23:01:10 -0800 Subject: [PATCH] better way to deal with empty bodies --- api.go | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/api.go b/api.go index 9197b0c..8c39698 100644 --- a/api.go +++ b/api.go @@ -2,8 +2,6 @@ package main import ( "encoding/json" - "io/ioutil" - "log" "net/http" ) @@ -32,6 +30,7 @@ func apiInfo(w http.ResponseWriter, req *http.Request) { Name: "itslog", Routes: []string{ "/api/v0/info/", + "/api/v0/put/", }, } if err := json.NewEncoder(w).Encode(version); err != nil { @@ -46,24 +45,14 @@ func put(w http.ResponseWriter, req *http.Request) { return } - body, err := ioutil.ReadAll(req.Body) - if err != nil { - log.Printf("unable to read request body:", err) - } - req.Body.Close() - message := LogMessage{} - if *verbose { - log.Printf("incoming: '%s'", body) - } - parse_err := json.Unmarshal(body, &message) - if parse_err != nil { + if err := json.NewDecoder(req.Body).Decode(&message); err != nil { b, _ := json.Marshal(JSONError{err.Error()}) - http.Error(w, string(b), http.StatusMethodNotAllowed) + http.Error(w, string(b), http.StatusBadRequest) return } - _, err = message.save() + _, err := message.save() if err != nil { b, _ := json.Marshal(JSONError{err.Error()}) http.Error(w, string(b), http.StatusMethodNotAllowed)