json.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package web
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "github.com/kellegous/go/context"
  7. )
  8. // Used as an API response, this is a route with its associated shortcut name.
  9. type routeWithName struct {
  10. Name string `json:"name"`
  11. *context.Route
  12. }
  13. // The response type for all API responses.
  14. type msg struct {
  15. Ok bool `json:"ok"`
  16. Error string `json:"error,omitempty"`
  17. Route *routeWithName `json:"route,omitempty"`
  18. }
  19. // Encode the given data to JSON and send it to the client.
  20. func writeJSON(w http.ResponseWriter, data interface{}, status int) {
  21. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  22. w.WriteHeader(status)
  23. if err := json.NewEncoder(w).Encode(data); err != nil {
  24. log.Panic(err)
  25. }
  26. }
  27. // Encode a simple success msg and send it to the client.
  28. func writeJSONOk(w http.ResponseWriter) {
  29. writeJSON(w, &msg{
  30. Ok: true,
  31. }, http.StatusOK)
  32. }
  33. // Encode an error response and send it to the client.
  34. func writeJSONError(w http.ResponseWriter, err string) {
  35. writeJSON(w, &msg{
  36. Ok: false,
  37. Error: err,
  38. }, http.StatusOK)
  39. }
  40. // Encode a generic backend error and send it to the client.
  41. func writeJSONBackendError(w http.ResponseWriter, err error) {
  42. log.Printf("[error] %s", err)
  43. writeJSONError(w, "backend error")
  44. }
  45. // Encode the given named route as a msg and send it to the client.
  46. func writeJSONRoute(w http.ResponseWriter, name string, rt *context.Route) {
  47. writeJSON(w, &msg{
  48. Ok: true,
  49. Route: &routeWithName{
  50. Name: name,
  51. Route: rt,
  52. },
  53. }, http.StatusOK)
  54. }