-
Notifications
You must be signed in to change notification settings - Fork 19
/
client.go
95 lines (76 loc) · 1.62 KB
/
client.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* UpdateHub
* Copyright (C) 2017
* O.S. Systems Sofware LTDA: contato@ossystems.com.br
*
* SPDX-License-Identifier: Apache-2.0
*/
package client
import (
"errors"
"fmt"
"net"
"net/http"
"time"
)
// TODO: https support
const (
UpgradesEndpoint = "/upgrades"
StateReportEndpoint = "/report"
)
const defaultRedirectLimit = 10
var ErrMaxRedirect = errors.New("Exceeded max redirects")
var defaultHttpTransport = http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 30 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
type ApiClient struct {
http.Client
server string
}
func (client *ApiClient) Request() *ApiRequest {
return &ApiRequest{
client: client,
}
}
func NewApiClient(server string) *ApiClient {
return &ApiClient{
Client: http.Client{
Transport: &defaultHttpTransport,
CheckRedirect: checkRedirect,
},
server: server,
}
}
type ApiRequest struct {
client *ApiClient
}
type ApiRequester interface {
Client() *ApiClient
Do(req *http.Request) (*http.Response, error)
}
func (r *ApiRequest) Client() *ApiClient {
return r.client
}
func (r *ApiRequest) Do(req *http.Request) (*http.Response, error) {
return r.client.Do(req)
}
func serverURL(c *ApiClient, path string) string {
return fmt.Sprintf("%s/%s", c.server, path[1:])
}
func checkRedirect(req *http.Request, via []*http.Request) error {
if len(via) > defaultRedirectLimit {
return ErrMaxRedirect
}
if len(via) > 0 {
for key, val := range via[0].Header {
req.Header[key] = val
}
}
return nil
}