2013-12-20 23:11:01 -08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JsonHandler func(http.ResponseWriter, *http.Request)
|
|
|
|
|
|
|
|
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
h(w, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
type JSONError struct {
|
|
|
|
Reason string `json:"reason"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type JSONMessage struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func apiInfo(w http.ResponseWriter, req *http.Request) {
|
|
|
|
version := struct {
|
|
|
|
Version string `json:"version"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Routes []string `json:"routes"`
|
|
|
|
}{
|
|
|
|
Version: "0.1",
|
|
|
|
Name: "itslog",
|
|
|
|
Routes: []string{
|
|
|
|
"/api/v0/info/",
|
2013-12-28 23:01:10 -08:00
|
|
|
"/api/v0/put/",
|
2013-12-20 23:11:01 -08:00
|
|
|
},
|
|
|
|
}
|
|
|
|
if err := json.NewEncoder(w).Encode(version); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
2013-12-20 23:37:17 -08:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
message := LogMessage{}
|
2013-12-28 23:01:10 -08:00
|
|
|
if err := json.NewDecoder(req.Body).Decode(&message); err != nil {
|
2013-12-21 00:26:54 -08:00
|
|
|
b, _ := json.Marshal(JSONError{err.Error()})
|
2013-12-28 23:01:10 -08:00
|
|
|
http.Error(w, string(b), http.StatusBadRequest)
|
2013-12-20 23:37:17 -08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-12-28 23:01:10 -08:00
|
|
|
_, err := message.save()
|
2013-12-20 23:37:17 -08:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|