Browse Source

Added original /put/ api

- does not yet log to db
Stephen McQuay 5 years ago
parent
commit
fdbdb037c6
2 changed files with 46 additions and 0 deletions
  1. 45
    0
      api.go
  2. 1
    0
      main.go

+ 45
- 0
api.go View File

@@ -2,6 +2,8 @@ package main
2 2
 
3 3
 import (
4 4
 	"encoding/json"
5
+	"io/ioutil"
6
+	"log"
5 7
 	"net/http"
6 8
 )
7 9
 
@@ -20,6 +22,12 @@ type JSONMessage struct {
20 22
 	Message string `json:"message"`
21 23
 }
22 24
 
25
+type LogMessage struct {
26
+	Level     int         `json:"level"`
27
+	Namespace string      `json:"namespace"`
28
+	Payload   interface{} `json:"payload"`
29
+}
30
+
23 31
 func apiInfo(w http.ResponseWriter, req *http.Request) {
24 32
 	version := struct {
25 33
 		Version string   `json:"version"`
@@ -36,3 +44,40 @@ func apiInfo(w http.ResponseWriter, req *http.Request) {
36 44
 		http.Error(w, err.Error(), http.StatusInternalServerError)
37 45
 	}
38 46
 }
47
+
48
+func put(w http.ResponseWriter, req *http.Request) {
49
+	if req.Method != "POST" {
50
+		b, _ := json.Marshal(JSONError{"supported methods: POST"})
51
+		http.Error(w, string(b), http.StatusMethodNotAllowed)
52
+		return
53
+	}
54
+
55
+	body, err := ioutil.ReadAll(req.Body)
56
+	if err != nil {
57
+		log.Printf("unable to read request body:", err)
58
+	}
59
+	req.Body.Close()
60
+
61
+	message := LogMessage{}
62
+	if *verbose {
63
+		log.Printf("incoming: '%s'", body)
64
+	}
65
+	parse_err := json.Unmarshal(body, &message)
66
+	if parse_err != nil {
67
+		if err := json.NewEncoder(w).Encode(JSONError{parse_err.Error()}); err != nil {
68
+			http.Error(w, err.Error(), http.StatusInternalServerError)
69
+		}
70
+		return
71
+	}
72
+
73
+	_, err = json.Marshal(message.Payload)
74
+	if err != nil {
75
+		b, _ := json.Marshal(JSONError{err.Error()})
76
+		http.Error(w, string(b), http.StatusMethodNotAllowed)
77
+		return
78
+	}
79
+
80
+	if err := json.NewEncoder(w).Encode(JSONMessage{"ok"}); err != nil {
81
+		http.Error(w, err.Error(), http.StatusInternalServerError)
82
+	}
83
+}

+ 1
- 0
main.go View File

@@ -24,6 +24,7 @@ func main() {
24 24
 	log.Printf("%+v", config)
25 25
 
26 26
 	http.Handle("/api/v0/info/", JsonHandler(apiInfo))
27
+	http.Handle("/api/v0/put/", JsonHandler(put))
27 28
 
28 29
 	err = http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)
29 30
 	if err != nil {

Loading…
Cancel
Save