json.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package render
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/pkg/errors"
  6. )
  7. var jsonContentType = []string{"application/json; charset=utf-8"}
  8. // JSON common json struct.
  9. type JSON struct {
  10. Code int `json:"code"`
  11. Message string `json:"message"`
  12. TTL int `json:"ttl"`
  13. Data interface{} `json:"data,omitempty"`
  14. }
  15. func writeJSON(w http.ResponseWriter, obj interface{}) (err error) {
  16. var jsonBytes []byte
  17. writeContentType(w, jsonContentType)
  18. if jsonBytes, err = json.Marshal(obj); err != nil {
  19. err = errors.WithStack(err)
  20. return
  21. }
  22. if _, err = w.Write(jsonBytes); err != nil {
  23. err = errors.WithStack(err)
  24. }
  25. return
  26. }
  27. // Render (JSON) writes data with json ContentType.
  28. func (r JSON) Render(w http.ResponseWriter) error {
  29. // FIXME(zhoujiahui): the TTL field will be configurable in the future
  30. if r.TTL <= 0 {
  31. r.TTL = 1
  32. }
  33. return writeJSON(w, r)
  34. }
  35. // WriteContentType write json ContentType.
  36. func (r JSON) WriteContentType(w http.ResponseWriter) {
  37. writeContentType(w, jsonContentType)
  38. }
  39. // MapJSON common map json struct.
  40. type MapJSON map[string]interface{}
  41. // Render (MapJSON) writes data with json ContentType.
  42. func (m MapJSON) Render(w http.ResponseWriter) error {
  43. return writeJSON(w, m)
  44. }
  45. // WriteContentType write json ContentType.
  46. func (m MapJSON) WriteContentType(w http.ResponseWriter) {
  47. writeContentType(w, jsonContentType)
  48. }