From fdbdb037c61fe280171edf63d941633f7121111d Mon Sep 17 00:00:00 2001 From: Stephen McQuay Date: Fri, 20 Dec 2013 23:37:17 -0800 Subject: [PATCH] Added original /put/ api - does not yet log to db --- api.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ main.go | 1 + 2 files changed, 46 insertions(+) diff --git a/api.go b/api.go index 219491b..d086674 100644 --- a/api.go +++ b/api.go @@ -2,6 +2,8 @@ package main import ( "encoding/json" + "io/ioutil" + "log" "net/http" ) @@ -20,6 +22,12 @@ type JSONMessage struct { Message string `json:"message"` } +type LogMessage struct { + Level int `json:"level"` + Namespace string `json:"namespace"` + Payload interface{} `json:"payload"` +} + func apiInfo(w http.ResponseWriter, req *http.Request) { version := struct { Version string `json:"version"` @@ -36,3 +44,40 @@ func apiInfo(w http.ResponseWriter, req *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) } } + +func put(w http.ResponseWriter, req *http.Request) { + if req.Method != "POST" { + b, _ := json.Marshal(JSONError{"supported methods: POST"}) + http.Error(w, string(b), http.StatusMethodNotAllowed) + 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.NewEncoder(w).Encode(JSONError{parse_err.Error()}); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + _, err = json.Marshal(message.Payload) + if err != nil { + b, _ := json.Marshal(JSONError{err.Error()}) + http.Error(w, string(b), http.StatusMethodNotAllowed) + return + } + + if err := json.NewEncoder(w).Encode(JSONMessage{"ok"}); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} diff --git a/main.go b/main.go index 75a1089..6437261 100644 --- a/main.go +++ b/main.go @@ -24,6 +24,7 @@ func main() { log.Printf("%+v", config) http.Handle("/api/v0/info/", JsonHandler(apiInfo)) + http.Handle("/api/v0/put/", JsonHandler(put)) err = http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil) if err != nil {