-
Notifications
You must be signed in to change notification settings - Fork 12
/
cmq_http.go
113 lines (100 loc) · 2.38 KB
/
cmq_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
package cmq_go
import (
"time"
"net/http"
"fmt"
"io/ioutil"
"net/url"
"bytes"
"errors"
"net"
)
const (
DEFAULT_HTTP_TIMEOUT = 3000 //ms
)
type CMQHttp struct {
isKeepAlive bool
conn *http.Client
}
var DefaultTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 500,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
func NewCMQHttp() *CMQHttp {
return &CMQHttp{
isKeepAlive: true,
conn: &http.Client{
Timeout: DEFAULT_HTTP_TIMEOUT * time.Millisecond,
Transport: DefaultTransport,
},
}
}
func (this *CMQHttp) setProxy(proxyUrlStr string) (err error) {
if proxyUrlStr == "" {
return
}
proxyUrl, err := url.Parse(proxyUrlStr)
if err != nil {
return
}
transport, err := this.getTransport()
if err != nil {
return
}
transport.Proxy = http.ProxyURL(proxyUrl)
return
}
func (this *CMQHttp) unsetProxy() (err error) {
transport, err := this.getTransport()
if err != nil {
return
}
transport.Proxy = nil
return
}
func (this *CMQHttp) getTransport() (*http.Transport, error) {
if this.conn.Transport == nil {
this.SetTransport(DefaultTransport)
}
if transport, ok := this.conn.Transport.(*http.Transport); ok {
return transport, nil
}
return nil, errors.New("transport is not an *http.Transport instance")
}
func (this *CMQHttp) SetTransport(transport http.RoundTripper) {
this.conn.Transport = transport
}
func (this *CMQHttp) request(method, urlStr, reqStr string, userTimeout int) (result string, err error) {
timeout := DEFAULT_HTTP_TIMEOUT
if userTimeout >= 0 {
timeout += userTimeout
}
this.conn.Timeout = time.Duration(timeout) * time.Millisecond
req, err := http.NewRequest(method, urlStr, bytes.NewReader([]byte(reqStr)))
if err != nil {
return "", fmt.Errorf("make http req error %v", err)
}
resp, err := this.conn.Do(req)
if err != nil {
return "", fmt.Errorf("http error %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("http error code %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read http resp body error %v", err)
}
result = string(body)
return
}