-
Notifications
You must be signed in to change notification settings - Fork 7
/
api.go
78 lines (65 loc) · 1.65 KB
/
api.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
78
package devicecheck
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
const (
developmentBaseURL = "https://api.development.devicecheck.apple.com/v1"
productionBaseURL = "https://api.devicecheck.apple.com/v1"
)
func newBaseURL(env Environment) string {
switch env {
case Development:
return developmentBaseURL
case Production:
return productionBaseURL
default:
return developmentBaseURL
}
}
type api struct {
client *http.Client
baseURL string
}
func newAPI(env Environment) api {
return api{
client: http.DefaultClient,
baseURL: newBaseURL(env),
}
}
func newAPIWithHTTPClient(client *http.Client, env Environment) api {
return api{
client: client,
baseURL: newBaseURL(env),
}
}
func (api api) do(ctx context.Context, jwt, path string, requestBody interface{}) (int, string, error) {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(requestBody); err != nil {
return 0, "", fmt.Errorf("json: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api.baseURL+path, buf)
if err != nil {
return 0, "", fmt.Errorf("http: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", jwt))
req.Header.Set("User-Agent", "device-check-go (+https://github.com/rinchsan/device-check-go)")
resp, err := api.client.Do(req)
if err != nil {
var traceID string
if resp != nil {
traceID = resp.Header.Get("x-b3-traceid")
}
return 0, "", fmt.Errorf("http: %w: x-b3-traceid: %s", err, traceID)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return 0, "", fmt.Errorf("io: %w", err)
}
return resp.StatusCode, string(respBody), nil
}