-
Notifications
You must be signed in to change notification settings - Fork 1
/
servers.go
90 lines (79 loc) · 1.98 KB
/
servers.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
83
84
85
86
87
88
89
90
package nordapi
import (
"fmt"
"strconv"
)
// ErrServerNotFound is returned when no servers are found.
type ErrServerNotFound struct {
Filters []Filter
URL string
}
// Error implements error
func (e ErrServerNotFound) Error() string {
if len(e.Filters) > 0 {
return fmt.Sprintf("server not found, filters: %v", e.Filters)
}
return "server not found"
}
// String implements fmt.Stringer
func (e ErrServerNotFound) String() string {
if e.URL == "" {
return "error server not found"
}
return fmt.Sprintf("error no servers found at \"%v\"", e.URL)
}
// ServerList is a list of NordVPN servers
type ServerList []*Server
// Servers returns a complete list of NordVPN servers.
func Servers() (ServerList, error) {
var servers []Server
err := getAndUnmarshall("https://api.nordvpn.com/v1/servers?limit=16384", &servers)
if err != nil {
return nil, err
}
sl := make(ServerList, len(servers))
for i := range servers {
sl[i] = &servers[i]
}
return sl, nil
}
// Reccomended returns the top n recomended servers, filtered by filters.
func Reccomended(n int, filters ...Filter) (ServerList, error) {
s := strconv.Itoa(n)
var servers ServerList
f := FilterList(filters).GetFilter()
url := "https://api.nordvpn.com/v1/servers/recommendations"
if f != "" {
url += "?" + f + "&limit=" + s
} else {
url += "?limit=" + s
}
err := getAndUnmarshall(url, &servers)
if err != nil {
return nil, err
}
if len(servers) == 0 {
return nil, ErrServerNotFound{Filters: filters}
}
return servers, nil
}
// Hostname returns the server with the given hostname
func (sl ServerList) Hostname(hostname string) (*Server, error) {
for i := range sl {
if sl[i].Hostname == hostname {
return sl[i], nil
}
}
return nil, ErrServerNotFound{}
}
// Filter filters servers satisfying the given filters.
func (sl ServerList) Filter(filters ...Filter) ServerList {
fl := FilterList(filters)
var nsl ServerList
for _, s := range sl {
if fl.Satisfies(s) {
nsl = append(nsl, s)
}
}
return nsl
}