string.go 852 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package render
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. )
  8. var plainContentType = []string{"text/plain; charset=utf-8"}
  9. // String common string struct.
  10. type String struct {
  11. Format string
  12. Data []interface{}
  13. }
  14. // Render (String) writes data with custom ContentType.
  15. func (r String) Render(w http.ResponseWriter) error {
  16. return writeString(w, r.Format, r.Data)
  17. }
  18. // WriteContentType writes string with text/plain ContentType.
  19. func (r String) WriteContentType(w http.ResponseWriter) {
  20. writeContentType(w, plainContentType)
  21. }
  22. func writeString(w http.ResponseWriter, format string, data []interface{}) (err error) {
  23. writeContentType(w, plainContentType)
  24. if len(data) > 0 {
  25. _, err = fmt.Fprintf(w, format, data...)
  26. } else {
  27. _, err = io.WriteString(w, format)
  28. }
  29. if err != nil {
  30. err = errors.WithStack(err)
  31. }
  32. return
  33. }