better way to deal with empty bodies

This commit is contained in:
Stephen McQuay 2013-12-28 23:01:10 -08:00
parent ae10b4087a
commit efdae319fe
1 changed files with 4 additions and 15 deletions

19
api.go
View File

@ -2,8 +2,6 @@ package main
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"log"
"net/http" "net/http"
) )
@ -32,6 +30,7 @@ func apiInfo(w http.ResponseWriter, req *http.Request) {
Name: "itslog", Name: "itslog",
Routes: []string{ Routes: []string{
"/api/v0/info/", "/api/v0/info/",
"/api/v0/put/",
}, },
} }
if err := json.NewEncoder(w).Encode(version); err != nil { if err := json.NewEncoder(w).Encode(version); err != nil {
@ -46,24 +45,14 @@ func put(w http.ResponseWriter, req *http.Request) {
return return
} }
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("unable to read request body:", err)
}
req.Body.Close()
message := LogMessage{} message := LogMessage{}
if *verbose { if err := json.NewDecoder(req.Body).Decode(&message); err != nil {
log.Printf("incoming: '%s'", body)
}
parse_err := json.Unmarshal(body, &message)
if parse_err != nil {
b, _ := json.Marshal(JSONError{err.Error()}) b, _ := json.Marshal(JSONError{err.Error()})
http.Error(w, string(b), http.StatusMethodNotAllowed) http.Error(w, string(b), http.StatusBadRequest)
return return
} }
_, err = message.save() _, err := message.save()
if err != nil { if err != nil {
b, _ := json.Marshal(JSONError{err.Error()}) b, _ := json.Marshal(JSONError{err.Error()})
http.Error(w, string(b), http.StatusMethodNotAllowed) http.Error(w, string(b), http.StatusMethodNotAllowed)