Utilities for a JSON-based API.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

54 строки
1.3 KiB

  1. package impart
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. )
  7. type (
  8. // envelope contains metadata and optional data for a response object.
  9. envelope struct {
  10. Code int `json:"code"`
  11. ErrorType string `json:"error_type,omitempty"`
  12. ErrorMessage string `json:"error_msg,omitempty"`
  13. Data interface{} `json:"data,omitempty"`
  14. }
  15. )
  16. func writeBody(w http.ResponseWriter, body []byte, status int, contentType string) error {
  17. w.Header().Set("Content-Type", contentType+"; charset=UTF-8")
  18. w.Header().Set("Content-Length", strconv.Itoa(len(body)))
  19. w.WriteHeader(status)
  20. _, err := w.Write(body)
  21. return err
  22. }
  23. func renderJSON(w http.ResponseWriter, value interface{}, status int) error {
  24. body, err := json.Marshal(value)
  25. if err != nil {
  26. return err
  27. }
  28. return writeBody(w, body, status, "application/json")
  29. }
  30. func renderString(w http.ResponseWriter, status int, msg string) error {
  31. return writeBody(w, []byte(msg), status, "text/plain")
  32. }
  33. func WriteSuccess(w http.ResponseWriter, data interface{}, status int) error {
  34. env := &envelope{
  35. Code: status,
  36. Data: data,
  37. }
  38. return renderJSON(w, env, status)
  39. }
  40. func WriteError(w http.ResponseWriter, e HTTPError) error {
  41. env := &envelope{
  42. Code: e.Status,
  43. ErrorMessage: e.Message,
  44. }
  45. return renderJSON(w, env, e.Status)
  46. }