84 lines
1.9 KiB
Go
84 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"log"
|
|
"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"`
|
|
}
|
|
|
|
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"`
|
|
Name string `json:"name"`
|
|
Routes []string `json:"routes"`
|
|
}{
|
|
Version: "0.1",
|
|
Name: "itslog",
|
|
Routes: []string{
|
|
"/api/v0/info/",
|
|
},
|
|
}
|
|
if err := json.NewEncoder(w).Encode(version); err != nil {
|
|
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)
|
|
}
|
|
}
|