json.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package web
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "github.com/kellegous/go/internal"
  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. SourceHost string `json:"source_host"`
  12. *internal.Route
  13. }
  14. // The response type for all API responses.
  15. type msg struct {
  16. Ok bool `json:"ok"`
  17. }
  18. type msgErr struct {
  19. Ok bool `json:"ok"`
  20. Error string `json:"error"`
  21. }
  22. type msgRoute struct {
  23. Ok bool `json:"ok"`
  24. Route *routeWithName `json:"route"`
  25. }
  26. type msgRoutes struct {
  27. Ok bool `json:"ok"`
  28. Routes []*routeWithName `json:"routes"`
  29. Next string `json:"next"`
  30. }
  31. // Encode the given data to JSON and send it to the client.
  32. func writeJSON(w http.ResponseWriter, data interface{}, status int) {
  33. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  34. w.WriteHeader(status)
  35. if err := json.NewEncoder(w).Encode(data); err != nil {
  36. log.Panic(err)
  37. }
  38. }
  39. // Encode a simple success msg and send it to the client.
  40. func writeJSONOk(w http.ResponseWriter) {
  41. writeJSON(w, &msg{
  42. Ok: true,
  43. }, http.StatusOK)
  44. }
  45. // Encode an error response and send it to the client.
  46. func writeJSONError(w http.ResponseWriter, err string, status int) {
  47. writeJSON(w, &msgErr{
  48. Ok: false,
  49. Error: err,
  50. }, status)
  51. }
  52. // Encode a generic backend error and send it to the client.
  53. func writeJSONBackendError(w http.ResponseWriter, err error) {
  54. log.Printf("[error] %s", err)
  55. writeJSONError(w, "backend error", http.StatusInternalServerError)
  56. }
  57. // Encode the given named route as a msg and send it to the client.
  58. func writeJSONRoute(w http.ResponseWriter, name string, rt *internal.Route, host string) {
  59. r := routeWithName{
  60. Name: name,
  61. Route: rt,
  62. }
  63. if host != "" {
  64. r.SourceHost = host
  65. }
  66. writeJSON(w, &msgRoute{
  67. Ok: true,
  68. Route: &r,
  69. }, http.StatusOK)
  70. }