json.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "bytes"
  7. "encoding/json"
  8. "net/http"
  9. )
  10. type JSON struct {
  11. Data interface{}
  12. }
  13. type IndentedJSON struct {
  14. Data interface{}
  15. }
  16. type SecureJSON struct {
  17. Prefix string
  18. Data interface{}
  19. }
  20. type SecureJSONPrefix string
  21. var jsonContentType = []string{"application/json; charset=utf-8"}
  22. func (r JSON) Render(w http.ResponseWriter) (err error) {
  23. if err = WriteJSON(w, r.Data); err != nil {
  24. panic(err)
  25. }
  26. return
  27. }
  28. func (r JSON) WriteContentType(w http.ResponseWriter) {
  29. writeContentType(w, jsonContentType)
  30. }
  31. func WriteJSON(w http.ResponseWriter, obj interface{}) error {
  32. writeContentType(w, jsonContentType)
  33. jsonBytes, err := json.Marshal(obj)
  34. if err != nil {
  35. return err
  36. }
  37. w.Write(jsonBytes)
  38. return nil
  39. }
  40. func (r IndentedJSON) Render(w http.ResponseWriter) error {
  41. r.WriteContentType(w)
  42. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  43. if err != nil {
  44. return err
  45. }
  46. w.Write(jsonBytes)
  47. return nil
  48. }
  49. func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
  50. writeContentType(w, jsonContentType)
  51. }
  52. func (r SecureJSON) Render(w http.ResponseWriter) error {
  53. r.WriteContentType(w)
  54. jsonBytes, err := json.Marshal(r.Data)
  55. if err != nil {
  56. return err
  57. }
  58. // if the jsonBytes is array values
  59. if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {
  60. w.Write([]byte(r.Prefix))
  61. }
  62. w.Write(jsonBytes)
  63. return nil
  64. }
  65. func (r SecureJSON) WriteContentType(w http.ResponseWriter) {
  66. writeContentType(w, jsonContentType)
  67. }