json.go 587 B

123456789101112131415161718192021222324252627282930313233
  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. const jsonContentType = "application/json; charset=utf-8"
  15. func (r JSON) Write(w http.ResponseWriter) error {
  16. w.Header().Set("Content-Type", jsonContentType)
  17. return json.NewEncoder(w).Encode(r.Data)
  18. }
  19. func (r IndentedJSON) Write(w http.ResponseWriter) error {
  20. w.Header().Set("Content-Type", jsonContentType)
  21. jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
  22. if err != nil {
  23. return err
  24. }
  25. w.Write(jsonBytes)
  26. return nil
  27. }