Skip to content

Commit

Permalink
chore: avoid using mimetype detector if key already exists (thx @Hout…
Browse files Browse the repository at this point in the history
  • Loading branch information
thoas committed Sep 26, 2023
1 parent a97c4c3 commit 8a43973
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
18 changes: 13 additions & 5 deletions middleware/parsers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/gin-gonic/gin"

"github.com/thoas/picfit"
"github.com/thoas/picfit/constants"
"github.com/thoas/picfit/engine"
"github.com/thoas/picfit/hash"
Expand Down Expand Up @@ -102,15 +103,23 @@ func setParamsFromURLValues(params map[string]interface{}, values url.Values) ma
}

// URLParser extracts the url query string and add a url.URL to the context
func URLParser(mimetypeDetectorType string) gin.HandlerFunc {
func URLParser(mimetypeDetectorType string, processor *picfit.Processor) gin.HandlerFunc {
mimetypeDetector := image.GetMimetypeDetector(mimetypeDetectorType)

return func(c *gin.Context) {
value := c.Query("url")
if storeKey := c.MustGet("key").(string); storeKey != "" {
exists, err := processor.KeyExists(c.Request.Context(), storeKey)
if err != nil {
c.Abort()
}
if exists {
c.Next()
return
}
}

if value != "" {
if value := c.Query("url"); value != "" {
url, err := url.Parse(value)

if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("URL %s is not valid", value))
c.Abort()
Expand All @@ -120,7 +129,6 @@ func URLParser(mimetypeDetectorType string) gin.HandlerFunc {
mimetype, _ := mimetypeDetector(url)

_, ok := image.Extensions[mimetype]

if !ok {
c.String(http.StatusBadRequest, fmt.Sprintf("Mimetype %s is not supported", mimetype))
c.Abort()
Expand Down
2 changes: 1 addition & 1 deletion server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func (s *HTTPServer) Init() error {
middleware.ParametersParser(),
middleware.KeyParser(),
middleware.Security(s.config.SecretKey),
middleware.URLParser(s.config.Options.MimetypeDetector),
middleware.URLParser(s.config.Options.MimetypeDetector, s.processor),
middleware.OperationParser(),
middleware.RestrictSizes(s.config.Options.AllowedSizes),
e.handler,
Expand Down

0 comments on commit 8a43973

Please sign in to comment.