json.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 (
  10. JSON struct {
  11. Data interface{}
  12. }
  13. IndentedJSON struct {
  14. Data interface{}
  15. }
  16. )
  17. var jsonContentType = []string{"application/json; charset=utf-8"}
  18. func (r JSON) Render(w http.ResponseWriter) (err error) {
  19. if err = WriteJSON(w, r.Data); err != nil {
  20. panic(err)
  21. }
  22. return
  23. }
  24. func (r JSON) WriteContentType(w http.ResponseWriter) {
  25. writeContentType(w, jsonContentType)
  26. }
  27. func WriteJSON(w http.ResponseWriter, obj interface{}) error {
  28. writeContentType(w, jsonContentType)
  29. jsonBytes, err := json.Marshal(obj)
  30. if err != nil {
  31. return err
  32. }
  33. w.Write(jsonBytes)
  34. return nil
  35. }
  36. func (r IndentedJSON) Render(w http.ResponseWriter) error {
  37. r.WriteContentType(w)
  38. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  39. if err != nil {
  40. return err
  41. }
  42. w.Write(jsonBytes)
  43. return nil
  44. }
  45. func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
  46. writeContentType(w, jsonContentType)
  47. }