-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.go
36 lines (29 loc) · 805 Bytes
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package urlparser
import (
"net/url"
"regexp"
"strings"
)
func Format(rawUrl string, format string) (string, error) {
parsedUrl, err := url.Parse(rawUrl)
if err != nil {
return "", err
}
matches := regexp.MustCompile(`(?i){[a-z0-9:+-]+}`).FindAllString(format, -1)
if matches == nil {
return "", nil
}
requiredComponents := make(map[string]interface{})
for _, match := range matches {
requiredComponents[match] = nil
}
replacements := make([]string, 0, len(requiredComponents)*2)
for placeholder := range requiredComponents {
component, err := getComponent(parsedUrl, placeholder[1:len(placeholder)-1])
if err != nil {
return "", err
}
replacements = append(replacements, placeholder, component)
}
return strings.NewReplacer(replacements...).Replace(format), nil
}