-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
82 lines (67 loc) · 1.75 KB
/
url.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package geizhals
import (
"errors"
"fmt"
"log"
"strconv"
)
type EntityURL struct {
SubmittedURL string
CleanURL string
Path string
Location string
Locations []string
EntityID int64
Type EntityType
}
// parseGeizhalsURL parses the given URL and returns a EntityURL struct.
func parseGeizhalsURL(rawurl string) (EntityURL, error) {
var matches []string
var location string
entityType := Product
matches = productURLPattern.FindStringSubmatch(rawurl)
if len(matches) != 4 {
matches = wishlistURLPattern.FindStringSubmatch(rawurl)
entityType = Wishlist
}
if len(matches) != 4 {
return EntityURL{}, ErrInvalidURL
}
entityIDString := matches[3]
entityID, err := strconv.Atoi(entityIDString)
if err != nil {
return EntityURL{}, fmt.Errorf("couldn't parse entity ID: %s", entityIDString)
}
// Pick location from the domain name
locationTLDMatches := locationDomainPattern.FindStringSubmatch(rawurl)
for i, locationTLDMatch := range locationTLDMatches {
if locationTLDMatch == "" || i == 0 {
continue
}
location = locationTLDMatch
break
}
if location == "" {
log.Println("No location found for URL:", rawurl)
return EntityURL{}, errors.New("couldn't parse location")
}
ghURL := EntityURL{
SubmittedURL: rawurl,
CleanURL: matches[1],
Path: matches[2],
EntityID: int64(entityID),
Location: location,
Type: entityType,
}
return ghURL, nil
}
func LocationFromURL(rawurl string) (string, error) {
locationTLDMatches := locationDomainPattern.FindStringSubmatch(rawurl)
for i, locationTLDMatch := range locationTLDMatches {
if locationTLDMatch == "" || i == 0 {
continue
}
return locationTLDMatch, nil
}
return "", errors.New("couldn't parse location")
}