-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
65 lines (59 loc) · 1.19 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
package tools
import (
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
// HTTPCurl helpers for http requests
type HTTPCurl struct {
HTTPClient *http.Client
Timeout time.Duration
}
// NewHTTPCurl new http helper object
func NewHTTPCurl() *HTTPCurl {
h := &HTTPCurl{
Timeout: time.Duration(30),
}
h.Init()
return h
}
// Init start prep
func (g *HTTPCurl) Init() {
//web
g.HTTPClient = &http.Client{
Timeout: time.Duration(g.Timeout * time.Second),
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: g.Timeout * time.Second,
KeepAlive: 0,
}).Dial,
TLSHandshakeTimeout: g.Timeout * time.Second,
},
}
}
// Get request via get
func (g *HTTPCurl) Get(url string) (string, int, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", -1, err
}
//settings
req.Close = true
req.Header.Set("Connection", "close")
resp, err := g.HTTPClient.Do(req)
if err != nil {
if resp != nil {
resp.Body.Close()
}
return "", -1, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", resp.StatusCode, err
}
// read the body
return strings.TrimSpace(string(contents)), resp.StatusCode, nil
}