image.go 997 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package getter
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "github.com/microcosm-cc/bluemonday"
  9. )
  10. type Image struct {
  11. Blob []byte
  12. Mediatype string
  13. }
  14. func GetImage(urlStr string) (*Image, error) {
  15. if _, err := url.Parse(urlStr); err != nil {
  16. return nil, err
  17. }
  18. response, err := http.Get(urlStr)
  19. if err != nil {
  20. return nil, err
  21. }
  22. defer response.Body.Close()
  23. mediatype, err := getMediatype(response)
  24. if err != nil {
  25. return nil, err
  26. }
  27. if !strings.HasPrefix(mediatype, "image/") {
  28. return nil, errors.New("Wrong image mediatype")
  29. }
  30. bodyBytes, err := io.ReadAll(response.Body)
  31. if err != nil {
  32. return nil, err
  33. }
  34. bodyBytes, err = SanitizeContent(bodyBytes)
  35. if err != nil {
  36. return nil, err
  37. }
  38. image := &Image{
  39. Blob: bodyBytes,
  40. Mediatype: mediatype,
  41. }
  42. return image, nil
  43. }
  44. func SanitizeContent(content []byte) ([]byte, error) {
  45. bodyString := string(content)
  46. bm := bluemonday.UGCPolicy()
  47. return []byte(bm.Sanitize(bodyString)), nil
  48. }