This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
verifyProtocolVersion.go
63 lines (54 loc) · 1.54 KB
/
verifyProtocolVersion.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
package client
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/qbeon/webwire-go"
)
// verifyProtocolVersion requests the endpoint metadata
// to verify the server is running a supported protocol version
func (clt *Client) verifyProtocolVersion() error {
// Initialize HTTP client
var httpClient = &http.Client{
Timeout: time.Second * 10,
}
request, err := http.NewRequest(
"WEBWIRE", "http://"+clt.serverAddr+"/", nil,
)
if err != nil {
panic(fmt.Errorf("Couldn't create HTTP metadata request: %s", err))
}
response, err := httpClient.Do(request)
if err != nil {
return webwire.NewDisconnectedErr(fmt.Errorf(
"Endpoint metadata request failed: %s", err,
))
}
// Read response body
defer response.Body.Close()
encodedData, err := ioutil.ReadAll(response.Body)
if err != nil {
return webwire.NewProtocolErr(fmt.Errorf("Couldn't read metadata response body: %s", err))
}
if response.StatusCode == http.StatusServiceUnavailable {
return webwire.NewDisconnectedErr(fmt.Errorf("Endpoint unavailable: %s", response.Status))
}
// Unmarshal response
var metadata struct {
ProtocolVersion string `json:"protocol-version"`
}
if err := json.Unmarshal(encodedData, &metadata); err != nil {
return webwire.NewProtocolErr(fmt.Errorf(
"Couldn't parse HTTP metadata response ('%s'): %s",
string(encodedData),
err,
))
}
// Verify metadata
if metadata.ProtocolVersion != supportedProtocolVersion {
return webwire.NewConnIncompErr(metadata.ProtocolVersion, supportedProtocolVersion)
}
return nil
}