json.go 835 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) error {
  19. return WriteJSON(w, r.Data)
  20. }
  21. func (r IndentedJSON) Render(w http.ResponseWriter) error {
  22. writeContentType(w, jsonContentType)
  23. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  24. if err != nil {
  25. return err
  26. }
  27. w.Write(jsonBytes)
  28. return nil
  29. }
  30. func WriteJSON(w http.ResponseWriter, obj interface{}) error {
  31. writeContentType(w, jsonContentType)
  32. return json.NewEncoder(w).Encode(obj)
  33. }