123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package optionsparser
- 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)
- }
|