-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_go.go
82 lines (66 loc) · 1.62 KB
/
http_go.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
// +build !js
package ninchat
import (
"bytes"
"crypto/tls"
"io/ioutil"
"net/http"
"time"
)
const userAgentHeader = "User-Agent"
var tlsConfig = tls.Config{
PreferServerCipherSuites: true,
}
func init() {
t := http.DefaultTransport.(*http.Transport)
if t.TLSClientConfig != nil {
// In case a future Go version has it set.
t.TLSClientConfig.PreferServerCipherSuites = tlsConfig.PreferServerCipherSuites
} else {
// Support testing on best effort basis.
t.TLSClientConfig = &tlsConfig
}
}
type httpRequest http.Request
func newGetRequest(url string, header map[string][]string) (*httpRequest, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header = prepareHeader(header)
return (*httpRequest)(req), err
}
func newDataRequest(method, url string, header map[string][]string, data []byte) (*httpRequest, error) {
req, err := http.NewRequest(method, url, ioutil.NopCloser(bytes.NewReader(data)))
if err != nil {
return nil, err
}
req.Header = prepareHeader(header)
return (*httpRequest)(req), err
}
type httpResponse struct {
data []byte
err error
}
func getResponseData(req *httpRequest, timeout duration) (data []byte, err error) {
client := http.Client{
Timeout: time.Duration(timeout),
}
resp, err := client.Do((*http.Request)(req))
if err != nil {
return
}
if resp.Body != nil {
defer resp.Body.Close()
}
return ioutil.ReadAll(resp.Body)
}
func putResponseToChannel(req *httpRequest, timeout duration, c chan<- httpResponse) {
go func() {
data, err := getResponseData(req, timeout)
c <- httpResponse{
data: data,
err: err,
}
}()
}