store arbitrary json blobs in postgres over http
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type JsonHandler func(http.ResponseWriter, *http.Request)
  7. func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  8. w.Header().Set("Content-Type", "application/json")
  9. h(w, req)
  10. }
  11. type JSONError struct {
  12. Reason string `json:"reason"`
  13. }
  14. type JSONMessage struct {
  15. Message string `json:"message"`
  16. }
  17. func apiInfo(w http.ResponseWriter, req *http.Request) {
  18. version := struct {
  19. Version string `json:"version"`
  20. Name string `json:"name"`
  21. Routes []string `json:"routes"`
  22. }{
  23. Version: "0.1",
  24. Name: "itslog",
  25. Routes: []string{
  26. "/api/v0/info/",
  27. "/api/v0/put/",
  28. },
  29. }
  30. if err := json.NewEncoder(w).Encode(version); err != nil {
  31. http.Error(w, err.Error(), http.StatusInternalServerError)
  32. }
  33. }
  34. func put(w http.ResponseWriter, req *http.Request) {
  35. if req.Method != "POST" {
  36. b, _ := json.Marshal(JSONError{"supported methods: POST"})
  37. http.Error(w, string(b), http.StatusMethodNotAllowed)
  38. return
  39. }
  40. message := LogMessage{}
  41. if err := json.NewDecoder(req.Body).Decode(&message); err != nil {
  42. b, _ := json.Marshal(JSONError{err.Error()})
  43. http.Error(w, string(b), http.StatusBadRequest)
  44. return
  45. }
  46. _, err := message.save()
  47. if err != nil {
  48. b, _ := json.Marshal(JSONError{err.Error()})
  49. http.Error(w, string(b), http.StatusMethodNotAllowed)
  50. return
  51. }
  52. if err := json.NewEncoder(w).Encode(JSONMessage{"ok"}); err != nil {
  53. http.Error(w, err.Error(), http.StatusInternalServerError)
  54. }
  55. }