forked from google/exposure-notifications-server
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathenclient.go
77 lines (66 loc) · 1.88 KB
/
enclient.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
package enclient
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/google/exposure-notifications-server/internal/publish/model"
)
const (
// httpTimeout is the maximum amount of time to wait for a response.
httpTimeout = 30 * time.Second
)
type Interval int32
// Posts requests to the specified url.
// This methods attempts to serialize data argument as a json.
func PostRequest(url string, data interface{}) (*http.Response, error) {
request := bytes.NewBuffer(JsonRequest(data))
r, err := http.NewRequest("POST", url, request)
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: httpTimeout}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// Return error upstream.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to copy error body (%d): %w", resp.StatusCode, err)
}
return resp, fmt.Errorf("post request failed with status: %v\n%v", resp.StatusCode, body)
}
return resp, nil
}
// Serializes the given argument to json.
func JsonRequest(data interface{}) []byte {
jsonData, err := json.Marshal(data)
if err != nil {
log.Fatalf("unable to marshal json payload")
}
return jsonData
}
// Returns the Interval for the current moment of tme.
func NowInterval() Interval {
return NewInterval(time.Now().Unix())
}
// Creates a new interval for the UNIX epoch given.
func NewInterval(time int64) Interval {
return Interval(int32(time / 600))
}
// Creates an exposure key.
func ExposureKey(key string, intervalNumber Interval, intervalCount int32, transmissionRisk int) model.ExposureKey {
return model.ExposureKey{
Key: key,
IntervalNumber: int32(intervalNumber),
IntervalCount: intervalCount,
TransmissionRisk: transmissionRisk,
}
}