ShortcutURL returns the URL an Internet Shortcut file's content links to, read the way Windows reads it: the first URL= in the [InternetShortcut] section, ignoring case, comments, other keys and other sections. Content without that section and key, or whose URL isn't an http(s) URL as HTTPURL define
(content string)
| 68 | // without that section and key, or whose URL isn't an http(s) URL as HTTPURL |
| 69 | // defines it, is an error rather than a guess. |
| 70 | func ShortcutURL(content string) (string, error) { |
| 71 | // Windows saves some shortcuts with a UTF-8 byte order mark. |
| 72 | content = strings.TrimPrefix(content, "\ufeff") |
| 73 | |
| 74 | inSection, sawSection := false, false |
| 75 | for line := range strings.SplitSeq(content, "\n") { |
| 76 | line = strings.TrimSpace(line) |
| 77 | if strings.HasPrefix(line, ";") { |
| 78 | continue |
| 79 | } |
| 80 | if rest, ok := strings.CutPrefix(line, "["); ok { |
| 81 | name, _, _ := strings.Cut(rest, "]") |
| 82 | inSection = strings.EqualFold(strings.TrimSpace(name), "InternetShortcut") |
| 83 | sawSection = sawSection || inSection |
| 84 | continue |
| 85 | } |
| 86 | if !inSection { |
| 87 | continue |
| 88 | } |
| 89 | key, value, ok := strings.Cut(line, "=") |
| 90 | if !ok || !strings.EqualFold(strings.TrimSpace(key), "URL") { |
| 91 | continue |
| 92 | } |
| 93 | u, ok := HTTPURL(value) |
| 94 | if !ok { |
| 95 | return "", errors.New("the shortcut doesn't link to an http(s) URL") |
| 96 | } |
| 97 | return u, nil |
| 98 | } |
| 99 | |
| 100 | if !sawSection { |
| 101 | return "", ErrNoShortcutSection |
| 102 | } |
| 103 | return "", errors.New("no URL in the [InternetShortcut] section") |
| 104 | } |