http_getter.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package v1
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "github.com/labstack/echo/v4"
  7. getter "github.com/usememos/memos/plugin/http-getter"
  8. )
  9. func (*APIV1Service) registerGetterPublicRoutes(g *echo.Group) {
  10. // GET /get/image?url={url} - Get image.
  11. g.GET("/get/image", GetImage)
  12. }
  13. // GetImage godoc
  14. //
  15. // @Summary Get GetImage from URL
  16. // @Tags image-url
  17. // @Produce GetImage/*
  18. // @Param url query string true "Image url"
  19. // @Success 200 {object} nil "Image"
  20. // @Failure 400 {object} nil "Missing GetImage url | Wrong url | Failed to get GetImage url: %s"
  21. // @Failure 500 {object} nil "Failed to write GetImage blob"
  22. // @Router /o/get/GetImage [GET]
  23. func GetImage(c echo.Context) error {
  24. urlStr := c.QueryParam("url")
  25. if urlStr == "" {
  26. return echo.NewHTTPError(http.StatusBadRequest, "Missing image url")
  27. }
  28. if _, err := url.Parse(urlStr); err != nil {
  29. return echo.NewHTTPError(http.StatusBadRequest, "Wrong url").SetInternal(err)
  30. }
  31. image, err := getter.GetImage(urlStr)
  32. if err != nil {
  33. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to get image url: %s", urlStr)).SetInternal(err)
  34. }
  35. c.Response().Writer.WriteHeader(http.StatusOK)
  36. c.Response().Writer.Header().Set("Content-Type", image.Mediatype)
  37. c.Response().Writer.Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
  38. if _, err := c.Response().Writer.Write(image.Blob); err != nil {
  39. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to write image blob").SetInternal(err)
  40. }
  41. return nil
  42. }