json.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. }
  17. type msgErr struct {
  18. Ok bool `json:"ok"`
  19. Error string `json:"error"`
  20. }
  21. type msgRoute struct {
  22. Ok bool `json:"ok"`
  23. Route *routeWithName `json:"route"`
  24. }
  25. type msgRoutes struct {
  26. Ok bool `json:"ok"`
  27. Routes []*routeWithName `json:"routes"`
  28. Next string `json:"next"`
  29. }
  30. // Encode the given data to JSON and send it to the client.
  31. func writeJSON(w http.ResponseWriter, data interface{}, status int) {
  32. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  33. w.WriteHeader(status)
  34. if err := json.NewEncoder(w).Encode(data); err != nil {
  35. log.Panic(err)
  36. }
  37. }
  38. // Encode a simple success msg and send it to the client.
  39. func writeJSONOk(w http.ResponseWriter) {
  40. writeJSON(w, &msg{
  41. Ok: true,
  42. }, http.StatusOK)
  43. }
  44. // Encode an error response and send it to the client.
  45. func writeJSONError(w http.ResponseWriter, err string, status int) {
  46. writeJSON(w, &msgErr{
  47. Ok: false,
  48. Error: err,
  49. }, status)
  50. }
  51. // Encode a generic backend error and send it to the client.
  52. func writeJSONBackendError(w http.ResponseWriter, err error) {
  53. log.Printf("[error] %s", err)
  54. writeJSONError(w, "backend error", http.StatusInternalServerError)
  55. }
  56. // Encode the given named route as a msg and send it to the client.
  57. func writeJSONRoute(w http.ResponseWriter, name string, rt *context.Route) {
  58. writeJSON(w, &msgRoute{
  59. Ok: true,
  60. Route: &routeWithName{
  61. Name: name,
  62. Route: rt,
  63. },
  64. }, http.StatusOK)
  65. }