Debian Codegraph @

client/gethosts/gethost.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 // Package gethosts implements finding hosts to connect to for delivery of notifications.
18 package gethosts
19
20 import (
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io/ioutil"
25 "net/http"
26 "time"
27
28 "gitlab.com/ubports/development/core/lomiri-push-service/external/murmur3"
29 )
30
31 // GetHost implements finding hosts to connect to consulting a remote endpoint providing a hash of the device identifier.
32 type GetHost struct {
33 hash string
34 endpointUrl string
35 cli *http.Client
36 }
37
38 // New makes a GetHost.
39 func New(deviceId, endpointUrl string, timeout time.Duration) *GetHost {
40 hash := murmur3.Sum64([]byte(deviceId))
41 return &GetHost{
42 hash: fmt.Sprintf("%x", hash),
43 endpointUrl: endpointUrl,
44 cli: &http.Client{
45 Transport: &http.Transport{TLSHandshakeTimeout: timeout},
46 Timeout: timeout,
47 },
48 }
49 }
50
51 // Host contains the domain and hosts returned by the remote endpoint
52 type Host struct {
53 Domain string
54 Hosts []string
55 }
56
57 var (
58 ErrRequest = errors.New("request was not accepted")
59 ErrInternal = errors.New("remote had an internal error")
60 ErrTemporary = errors.New("remote had a temporary error")
61 )
62
63 // Get gets a list of hosts consulting the endpoint.
64 func (gh *GetHost) Get() (*Host, error) {
65 resp, err := gh.cli.Get(gh.endpointUrl + "?h=" + gh.hash)
66 if err != nil {
67 return nil, err
68 }
69 defer resp.Body.Close()
70 if resp.StatusCode != http.StatusOK {
71 switch {
72 case resp.StatusCode == http.StatusInternalServerError:
73 return nil, ErrInternal
74 case resp.StatusCode > http.StatusInternalServerError:
75 return nil, ErrTemporary
76 default:
77 return nil, ErrRequest
78 }
79 }
80 body, err := ioutil.ReadAll(resp.Body)
81 if err != nil {
82 return nil, err
83 }
84 var parsed Host
85 err = json.Unmarshal(body, &parsed)
86 if err != nil {
87 return nil, ErrTemporary
88 }
89 if len(parsed.Hosts) == 0 {
90 return nil, ErrTemporary
91 }
92 return &parsed, nil
93 }