csv.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package model
  2. import (
  3. "encoding/csv"
  4. "fmt"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. )
  8. // CSV Comma-Separated Values struct.
  9. type CSV struct {
  10. Data [][]string
  11. Title string
  12. }
  13. var csvContentType = []string{"text/csv; charset=utf-8"}
  14. // Render (CSV) writes data with CSV ContentType.
  15. func (c CSV) Render(w http.ResponseWriter) (err error) {
  16. c.WriteContentType(w)
  17. writer := csv.NewWriter(w)
  18. bomUtf8 := []byte{0xEF, 0xBB, 0xBF}
  19. writer.Write([]string{string(bomUtf8[:])})
  20. writer.WriteAll(c.Data)
  21. if err = writer.Error(); err != nil {
  22. err = errors.WithStack(err)
  23. }
  24. return
  25. }
  26. func writeContentType(w http.ResponseWriter, value []string, title string) {
  27. header := w.Header()
  28. if val := header["Content-Type"]; len(val) == 0 {
  29. header["Content-Type"] = value
  30. }
  31. if title != "" {
  32. header["Content-Disposition"] = append(header["Content-Disposition"], fmt.Sprintf("attachment; filename=%s.csv", title))
  33. }
  34. }
  35. // WriteContentType write CSV ContentType.
  36. func (c CSV) WriteContentType(w http.ResponseWriter) {
  37. writeContentType(w, csvContentType, c.Title)
  38. }