json.go 757 B

12345678910111213141516171819202122232425262728293031323334353637
  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) Write(w http.ResponseWriter) error {
  19. w.Header()["Content-Type"] = jsonContentType
  20. return json.NewEncoder(w).Encode(r.Data)
  21. }
  22. func (r IndentedJSON) Write(w http.ResponseWriter) error {
  23. w.Header()["Content-Type"] = jsonContentType
  24. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  25. if err != nil {
  26. return err
  27. }
  28. w.Write(jsonBytes)
  29. return nil
  30. }