/
user.go
76 lines (61 loc) · 1.9 KB
/
user.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
package speedtest
import (
"context"
"encoding/xml"
"errors"
"fmt"
"net/http"
)
const speedTestConfigUrl = "https://www.speedtest.net/speedtest-config.php"
// User represents information determined about the caller by speedtest.net
type User struct {
IP string `xml:"ip,attr"`
Lat string `xml:"lat,attr"`
Lon string `xml:"lon,attr"`
Isp string `xml:"isp,attr"`
}
// Users for decode xml
type Users struct {
Users []User `xml:"client"`
}
// FetchUserInfo returns information about caller determined by speedtest.net
func (s *Speedtest) FetchUserInfo() (*User, error) {
return s.FetchUserInfoContext(context.Background())
}
// FetchUserInfo returns information about caller determined by speedtest.net
func FetchUserInfo() (*User, error) {
return defaultClient.FetchUserInfo()
}
// FetchUserInfoContext returns information about caller determined by speedtest.net, observing the given context.
func (s *Speedtest) FetchUserInfoContext(ctx context.Context) (*User, error) {
dbg.Printf("Retrieving user info: %s\n", speedTestConfigUrl)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, speedTestConfigUrl, nil)
if err != nil {
return nil, err
}
resp, err := s.doer.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Decode xml
decoder := xml.NewDecoder(resp.Body)
var users Users
if err = decoder.Decode(&users); err != nil {
return nil, err
}
if len(users.Users) == 0 {
return nil, errors.New("failed to fetch user information")
}
s.User = &users.Users[0]
return s.User, nil
}
// FetchUserInfoContext returns information about caller determined by speedtest.net, observing the given context.
func FetchUserInfoContext(ctx context.Context) (*User, error) {
return defaultClient.FetchUserInfoContext(ctx)
}
// String representation of User
func (u *User) String() string {
extInfo := ""
return fmt.Sprintf("%s (%s) [%s, %s] %s", u.IP, u.Isp, u.Lat, u.Lon, extInfo)
}