-
Notifications
You must be signed in to change notification settings - Fork 46
/
http.go
235 lines (209 loc) · 5.85 KB
/
http.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package api
import (
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime/debug"
"strings"
"time"
"github.com/cli/go-gh/pkg/api"
"github.com/henvic/httpretty"
)
const (
accept = "Accept"
authorization = "Authorization"
contentType = "Content-Type"
github = "github.com"
jsonContentType = "application/json; charset=utf-8"
localhost = "github.localhost"
modulePath = "github.com/cli/go-gh"
timeZone = "Time-Zone"
userAgent = "User-Agent"
)
var jsonTypeRE = regexp.MustCompile(`[/+]json($|;)`)
var timeZoneNames = map[int]string{
-39600: "Pacific/Niue",
-36000: "Pacific/Honolulu",
-34200: "Pacific/Marquesas",
-32400: "America/Anchorage",
-28800: "America/Los_Angeles",
-25200: "America/Chihuahua",
-21600: "America/Chicago",
-18000: "America/Bogota",
-14400: "America/Caracas",
-12600: "America/St_Johns",
-10800: "America/Argentina/Buenos_Aires",
-7200: "Atlantic/South_Georgia",
-3600: "Atlantic/Cape_Verde",
0: "Europe/London",
3600: "Europe/Amsterdam",
7200: "Europe/Athens",
10800: "Europe/Istanbul",
12600: "Asia/Tehran",
14400: "Asia/Dubai",
16200: "Asia/Kabul",
18000: "Asia/Tashkent",
19800: "Asia/Kolkata",
20700: "Asia/Kathmandu",
21600: "Asia/Dhaka",
23400: "Asia/Rangoon",
25200: "Asia/Bangkok",
28800: "Asia/Manila",
31500: "Australia/Eucla",
32400: "Asia/Tokyo",
34200: "Australia/Darwin",
36000: "Australia/Brisbane",
37800: "Australia/Adelaide",
39600: "Pacific/Guadalcanal",
43200: "Pacific/Nauru",
46800: "Pacific/Auckland",
49500: "Pacific/Chatham",
50400: "Pacific/Kiritimati",
}
func NewHTTPClient(opts *api.ClientOptions) http.Client {
if opts == nil {
opts = &api.ClientOptions{}
}
transport := http.DefaultTransport
if opts.UnixDomainSocket != "" {
transport = newUnixDomainSocketRoundTripper(opts.UnixDomainSocket)
}
if opts.Transport != nil {
transport = opts.Transport
}
if opts.CacheDir == "" {
opts.CacheDir = filepath.Join(os.TempDir(), "gh-cli-cache")
}
if opts.EnableCache && opts.CacheTTL == 0 {
opts.CacheTTL = time.Hour * 24
}
c := cache{dir: opts.CacheDir, ttl: opts.CacheTTL}
transport = c.RoundTripper(transport)
if opts.Log != nil {
logger := &httpretty.Logger{
Time: true,
TLS: false,
Colors: false,
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
Formatters: []httpretty.Formatter{&httpretty.JSONFormatter{}},
MaxResponseBody: 10000,
}
logger.SetOutput(opts.Log)
logger.SetBodyFilter(func(h http.Header) (skip bool, err error) {
return !inspectableMIMEType(h.Get(contentType)), nil
})
transport = logger.RoundTripper(transport)
}
if opts.Headers == nil {
opts.Headers = map[string]string{}
}
if !opts.SkipResolution {
resolveHeaders(opts.Headers)
}
transport = newHeaderRoundTripper(opts.Host, opts.AuthToken, opts.Headers, transport)
return http.Client{Transport: transport, Timeout: opts.Timeout}
}
func inspectableMIMEType(t string) bool {
return strings.HasPrefix(t, "text/") || jsonTypeRE.MatchString(t)
}
func isSameDomain(requestHost, domain string) bool {
requestHost = strings.ToLower(requestHost)
domain = strings.ToLower(domain)
return (requestHost == domain) || strings.HasSuffix(requestHost, "."+domain)
}
func isEnterprise(host string) bool {
return host != github && host != localhost
}
func normalizeHostname(hostname string) string {
hostname = strings.ToLower(hostname)
if strings.HasSuffix(hostname, "."+github) {
return github
}
if strings.HasSuffix(hostname, "."+localhost) {
return localhost
}
return hostname
}
type headerRoundTripper struct {
headers map[string]string
host string
rt http.RoundTripper
}
func resolveHeaders(headers map[string]string) {
if _, ok := headers[contentType]; !ok {
headers[contentType] = jsonContentType
}
if _, ok := headers[userAgent]; !ok {
headers[userAgent] = "go-gh"
info, ok := debug.ReadBuildInfo()
if ok {
for _, dep := range info.Deps {
if dep.Path == modulePath {
headers[userAgent] += fmt.Sprintf(" %s", dep.Version)
break
}
}
}
}
if _, ok := headers[timeZone]; !ok {
tz := currentTimeZone()
if tz != "" {
headers[timeZone] = tz
}
}
if _, ok := headers[accept]; !ok {
// Preview for PullRequest.mergeStateStatus.
a := "application/vnd.github.merge-info-preview+json"
// Preview for visibility when RESTing repos into an org.
a += ", application/vnd.github.nebula-preview"
headers[accept] = a
}
}
func newHeaderRoundTripper(host string, authToken string, headers map[string]string, rt http.RoundTripper) http.RoundTripper {
if _, ok := headers[authorization]; !ok && authToken != "" {
headers[authorization] = fmt.Sprintf("token %s", authToken)
}
if len(headers) == 0 {
return rt
}
return headerRoundTripper{host: host, headers: headers, rt: rt}
}
func (hrt headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
for k, v := range hrt.headers {
// If the authorization header has been set and the request
// host is not in the same domain that was specified in the ClientOptions
// then do not add the authorization header to the request.
if k == authorization && !isSameDomain(req.URL.Hostname(), hrt.host) {
continue
}
// If the header is already set in the request, don't overwrite it.
if req.Header.Get(k) == "" {
req.Header.Set(k, v)
}
}
return hrt.rt.RoundTrip(req)
}
func newUnixDomainSocketRoundTripper(socketPath string) http.RoundTripper {
dial := func(network, addr string) (net.Conn, error) {
return net.Dial("unix", socketPath)
}
return &http.Transport{
Dial: dial,
DialTLS: dial,
DisableKeepAlives: true,
}
}
func currentTimeZone() string {
tz := time.Local.String()
if tz == "Local" {
_, offset := time.Now().Zone()
tz = timeZoneNames[offset]
}
return tz
}