json.go 564 B

12345678910111213141516171819202122232425262728293031
  1. package render
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type (
  7. JSON struct {
  8. Data interface{}
  9. }
  10. IndentedJSON struct {
  11. Data interface{}
  12. }
  13. )
  14. func (r JSON) Write(w http.ResponseWriter) error {
  15. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  16. return json.NewEncoder(w).Encode(r.Data)
  17. }
  18. func (r IndentedJSON) Write(w http.ResponseWriter) error {
  19. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  20. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  21. if err != nil {
  22. return err
  23. }
  24. w.Write(jsonBytes)
  25. return nil
  26. }