-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathping.go
58 lines (45 loc) · 1.05 KB
/
ping.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
package qcon
import (
"context"
"crypto/md5"
"encoding/json"
"fmt"
"net/http"
)
const pingPath = "/webman/pingpong.cgi?action=cors&quickconnect=true"
// Ping attempts a ping-pong request to the given URL and returns
// an MD5 hash of the ServerID from the response for use in verification.
func (c Client) Ping(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url+pingPath, nil)
if err != nil {
return "", err
}
httpClient := c.Client
if httpClient == nil {
httpClient = &http.Client{}
}
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", ErrPingFailure
}
var jsonResp struct {
Success bool
EZID string
}
err = json.NewDecoder(resp.Body).Decode(&jsonResp)
if err != nil {
return "", err
}
if !jsonResp.Success {
return "", ErrPingFailure
}
return jsonResp.EZID, nil
}
func verifyID(id, hash string) bool {
h := fmt.Sprintf("%x", md5.Sum([]byte(id)))
return h == hash
}