/
http.go
106 lines (94 loc) · 2.09 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
package pay
import (
"crypto/tls"
"github.com/astaxie/beego/httplib"
"github.com/astaxie/beego/logs"
"io/ioutil"
"net/http"
"strings"
"time"
)
var (
tokenServer string
tokenUsername string
tokenPassword string
payClientCertFile string
payClientKeyFile string
payClientRootCert string
HTTPC *HTTPClient
HTTPSC *HTTPSClient
)
func init() {
HTTPC = &HTTPClient{}
HTTPSC = NewHTTPSClient([]byte{}, []byte{})
}
// HTTPSClient HTTPS客户端结构
type HTTPSClient struct {
http.Client
}
// NewHTTPSClient 获取默认https客户端
func NewHTTPSClient(certPEMBlock, keyPEMBlock []byte) *HTTPSClient {
config := new(tls.Config)
if len(certPEMBlock) != 0 && len(keyPEMBlock) != 0 {
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if err != nil {
panic("load x509 cert error:" + err.Error())
return nil
}
config = &tls.Config{
Certificates: []tls.Certificate{
cert,
},
}
} else {
config = &tls.Config{
InsecureSkipVerify: true,
}
}
tr := &http.Transport{
TLSClientConfig: config,
}
client := http.Client{
Transport: tr,
Timeout: 15 * time.Second,
}
return &HTTPSClient{
Client: client,
}
}
// PostData 提交post数据
func (c *HTTPSClient) PostData(url string, contentType string, data string) ([]byte, error) {
req := httplib.Post(url)
req.Body(data)
req.Header("Content-Type", contentType)
resp, err := req.Response()
if err != nil {
logs.Error("post url:%s failed:%s", url, err)
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
// PostData 提交post数据
func (c *HTTPSClient) GetData(url string) ([]byte, error) {
req := httplib.Get(url)
resp, err := req.Response()
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
// HTTPClient http客户端
type HTTPClient struct {
http.Client
}
// PostData post数据
func (c *HTTPClient) PostData(url, format string, data string) ([]byte, error) {
resp, err := c.Post(url, format, strings.NewReader(data))
if err != nil {
panic(err)
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}