Files
imgproxy/options/url.go
2025-09-24 00:41:12 +06:00

91 lines
2.1 KiB
Go

package options
import (
"encoding/base64"
"fmt"
"net/url"
"strings"
)
const urlTokenPlain = "plain"
func (p *Parser) preprocessURL(u string) string {
for _, repl := range p.config.URLReplacements {
u = repl.Regexp.ReplaceAllString(u, repl.Replacement)
}
if len(p.config.BaseURL) == 0 || strings.HasPrefix(u, p.config.BaseURL) {
return u
}
return fmt.Sprintf("%s%s", p.config.BaseURL, u)
}
func (p *Parser) decodeBase64URL(parts []string) (string, string, error) {
var format string
if len(parts) > 1 && p.config.Base64URLIncludesFilename {
parts = parts[:len(parts)-1]
}
encoded := strings.Join(parts, "")
urlParts := strings.Split(encoded, ".")
if len(urlParts[0]) == 0 {
return "", "", newInvalidURLError("Image URL is empty")
}
if len(urlParts) > 2 {
return "", "", newInvalidURLError("Multiple formats are specified: %s", encoded)
}
if len(urlParts) == 2 && len(urlParts[1]) > 0 {
format = urlParts[1]
}
imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
if err != nil {
return "", "", newInvalidURLError("Invalid url encoding: %s", encoded)
}
return p.preprocessURL(string(imageURL)), format, nil
}
func (p *Parser) decodePlainURL(parts []string) (string, string, error) {
var format string
encoded := strings.Join(parts, "/")
urlParts := strings.Split(encoded, "@")
if len(urlParts[0]) == 0 {
return "", "", newInvalidURLError("Image URL is empty")
}
if len(urlParts) > 2 {
return "", "", newInvalidURLError("Multiple formats are specified: %s", encoded)
}
if len(urlParts) == 2 && len(urlParts[1]) > 0 {
format = urlParts[1]
}
unescaped, err := url.PathUnescape(urlParts[0])
if err != nil {
return "", "", newInvalidURLError("Invalid url encoding: %s", encoded)
}
return p.preprocessURL(unescaped), format, nil
}
func (p *Parser) DecodeURL(parts []string) (string, string, error) {
if len(parts) == 0 {
return "", "", newInvalidURLError("Image URL is empty")
}
if parts[0] == urlTokenPlain && len(parts) > 1 {
return p.decodePlainURL(parts[1:])
}
return p.decodeBase64URL(parts)
}