csv.go 1017 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package http
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/pkg/errors"
  6. )
  7. // CSVContentType
  8. var (
  9. CSVContentType = []string{"application/csv"}
  10. _ Render = CSV{}
  11. )
  12. // Render http reponse render.
  13. type Render interface {
  14. Render(http.ResponseWriter) error
  15. WriteContentType(w http.ResponseWriter)
  16. }
  17. // CSV str.
  18. type CSV struct {
  19. Content []byte
  20. Title string
  21. }
  22. // WriteContentType fn
  23. func (j CSV) WriteContentType(w http.ResponseWriter) {
  24. writeContentType(w, CSVContentType, j.Title)
  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. header["Content-Disposition"] = append(header["Content-Disposition"], fmt.Sprintf("attachment; filename=%s.csv", title))
  32. }
  33. // Render (JSON) writes data with json ContentType.
  34. func (j CSV) Render(w http.ResponseWriter) (err error) {
  35. if _, err = w.Write(j.Content); err != nil {
  36. err = errors.WithStack(err)
  37. }
  38. return
  39. }