json.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package render
  5. import (
  6. "encoding/json"
  7. "net/http"
  8. )
  9. type JSON struct {
  10. Data interface{}
  11. }
  12. type IndentedJSON struct {
  13. Data interface{}
  14. }
  15. var jsonContentType = []string{"application/json; charset=utf-8"}
  16. func (r JSON) Render(w http.ResponseWriter) (err error) {
  17. if err = WriteJSON(w, r.Data); err != nil {
  18. panic(err)
  19. }
  20. return
  21. }
  22. func (r JSON) WriteContentType(w http.ResponseWriter) {
  23. writeContentType(w, jsonContentType)
  24. }
  25. func WriteJSON(w http.ResponseWriter, obj interface{}) error {
  26. writeContentType(w, jsonContentType)
  27. jsonBytes, err := json.Marshal(obj)
  28. if err != nil {
  29. return err
  30. }
  31. w.Write(jsonBytes)
  32. return nil
  33. }
  34. func (r IndentedJSON) Render(w http.ResponseWriter) error {
  35. r.WriteContentType(w)
  36. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  37. if err != nil {
  38. return err
  39. }
  40. w.Write(jsonBytes)
  41. return nil
  42. }
  43. func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
  44. writeContentType(w, jsonContentType)
  45. }