-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
93 lines (82 loc) · 2.29 KB
/
util.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
package bchapi
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
const (
ConnTimeoutMS = 3000
ServeTimeoutMS = 5000
)
//HttpGet get method
func HttpGet(url string, connTimeoutMs int, serveTimeoutMs int) (str string, err error) {
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, time.Duration(connTimeoutMs)*time.Millisecond)
if err != nil {
return nil, err
}
c.SetDeadline(time.Now().Add(time.Duration(serveTimeoutMs) * time.Millisecond))
return c, nil
},
},
}
reqest, _ := http.NewRequest("GET", url, nil)
response, err := client.Do(reqest)
if err != nil {
err = fmt.Errorf("http failed, GET url:%s, reason:%s", url, err.Error())
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
err = fmt.Errorf("http status code error, GET url:%s, code:%d", url, response.StatusCode)
return
}
resBody, err := ioutil.ReadAll(response.Body)
if err != nil {
err = fmt.Errorf("cannot read http response, GET url:%s, reason:%s", url, err.Error())
return
}
str = string(resBody)
return
}
//HttpPost post method
func HttpPost(url string, data string, connTimeoutMs int, serveTimeoutMs int) (str string, err error) {
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, time.Duration(connTimeoutMs)*time.Millisecond)
if err != nil {
return nil, err
}
c.SetDeadline(time.Now().Add(time.Duration(serveTimeoutMs) * time.Millisecond))
return c, nil
},
},
}
body := strings.NewReader(data)
reqest, _ := http.NewRequest("POST", url, body)
reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := client.Do(reqest)
if err != nil {
err = fmt.Errorf("http failed, POST url:%s, reason:%s", url, err.Error())
fmt.Println(err.Error())
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
err = fmt.Errorf("http status code error, POST url:%s, code:%d", url, response.StatusCode)
return
}
respBody, err := ioutil.ReadAll(response.Body)
if err != nil {
err = fmt.Errorf("cannot read http response, POST url:%s, reason:%s", url, err.Error())
return
}
str = string(respBody)
return
}