Browse Source

better way to deal with empty bodies

Stephen McQuay 4 years ago
parent
commit
efdae319fe
1 changed files with 4 additions and 15 deletions
  1. 4
    15
      api.go

+ 4
- 15
api.go View File

@@ -2,8 +2,6 @@ package main
2 2
 
3 3
 import (
4 4
 	"encoding/json"
5
-	"io/ioutil"
6
-	"log"
7 5
 	"net/http"
8 6
 )
9 7
 
@@ -32,6 +30,7 @@ func apiInfo(w http.ResponseWriter, req *http.Request) {
32 30
 		Name:    "itslog",
33 31
 		Routes: []string{
34 32
 			"/api/v0/info/",
33
+			"/api/v0/put/",
35 34
 		},
36 35
 	}
37 36
 	if err := json.NewEncoder(w).Encode(version); err != nil {
@@ -46,24 +45,14 @@ func put(w http.ResponseWriter, req *http.Request) {
46 45
 		return
47 46
 	}
48 47
 
49
-	body, err := ioutil.ReadAll(req.Body)
50
-	if err != nil {
51
-		log.Printf("unable to read request body:", err)
52
-	}
53
-	req.Body.Close()
54
-
55 48
 	message := LogMessage{}
56
-	if *verbose {
57
-		log.Printf("incoming: '%s'", body)
58
-	}
59
-	parse_err := json.Unmarshal(body, &message)
60
-	if parse_err != nil {
49
+	if err := json.NewDecoder(req.Body).Decode(&message); err != nil {
61 50
 		b, _ := json.Marshal(JSONError{err.Error()})
62
-		http.Error(w, string(b), http.StatusMethodNotAllowed)
51
+		http.Error(w, string(b), http.StatusBadRequest)
63 52
 		return
64 53
 	}
65 54
 
66
-	_, err = message.save()
55
+	_, err := message.save()
67 56
 	if err != nil {
68 57
 		b, _ := json.Marshal(JSONError{err.Error()})
69 58
 		http.Error(w, string(b), http.StatusMethodNotAllowed)