render_image.go 970 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package http
  2. import (
  3. "net/http"
  4. "github.com/pkg/errors"
  5. )
  6. var (
  7. imageContentType = []string{"image/jpeg"}
  8. _ Render = Image{}
  9. )
  10. // Render http reponse render.
  11. type Render interface {
  12. // Render render it to http response writer.
  13. Render(http.ResponseWriter) error
  14. // WriteContentType write content-type to http response writer.
  15. WriteContentType(w http.ResponseWriter)
  16. }
  17. // Image Image.
  18. type Image struct {
  19. Body []byte
  20. }
  21. // WriteContentType write json ContentType.
  22. func (j Image) WriteContentType(w http.ResponseWriter) {
  23. writeContentType(w, imageContentType)
  24. }
  25. func writeContentType(w http.ResponseWriter, value []string) {
  26. header := w.Header()
  27. if val := header["Content-Type"]; len(val) == 0 {
  28. header["Content-Type"] = value
  29. }
  30. }
  31. // Render (JSON) writes data with json ContentType.
  32. func (j Image) Render(w http.ResponseWriter) (err error) {
  33. if _, err = w.Write(j.Body); err != nil {
  34. err = errors.WithStack(err)
  35. }
  36. return
  37. }