url.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package options
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "fmt"
  6. "net/url"
  7. "strings"
  8. "github.com/imgproxy/imgproxy/v3/config"
  9. )
  10. const urlTokenPlain = "plain"
  11. func preprocessURL(u string) string {
  12. for _, repl := range config.URLReplacements {
  13. u = repl.Regexp.ReplaceAllString(u, repl.Replacement)
  14. }
  15. if len(config.BaseURL) == 0 || strings.HasPrefix(u, config.BaseURL) {
  16. return u
  17. }
  18. return fmt.Sprintf("%s%s", config.BaseURL, u)
  19. }
  20. func decodeBase64URL(parts []string) (string, string, error) {
  21. var format string
  22. encoded := strings.Join(parts, "")
  23. urlParts := strings.Split(encoded, ".")
  24. if len(urlParts[0]) == 0 {
  25. return "", "", errors.New("Image URL is empty")
  26. }
  27. if len(urlParts) > 2 {
  28. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  29. }
  30. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  31. format = urlParts[1]
  32. }
  33. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  34. if err != nil {
  35. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  36. }
  37. return preprocessURL(string(imageURL)), format, nil
  38. }
  39. func decodePlainURL(parts []string) (string, string, error) {
  40. var format string
  41. encoded := strings.Join(parts, "/")
  42. urlParts := strings.Split(encoded, "@")
  43. if len(urlParts[0]) == 0 {
  44. return "", "", errors.New("Image URL is empty")
  45. }
  46. if len(urlParts) > 2 {
  47. return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
  48. }
  49. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  50. format = urlParts[1]
  51. }
  52. unescaped, err := url.PathUnescape(urlParts[0])
  53. if err != nil {
  54. return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
  55. }
  56. return preprocessURL(unescaped), format, nil
  57. }
  58. func DecodeURL(parts []string) (string, string, error) {
  59. if len(parts) == 0 {
  60. return "", "", errors.New("Image URL is empty")
  61. }
  62. if parts[0] == urlTokenPlain && len(parts) > 1 {
  63. return decodePlainURL(parts[1:])
  64. }
  65. return decodeBase64URL(parts)
  66. }