-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
90 lines (76 loc) · 1.76 KB
/
client.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
package cli
import (
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/razielsd/antibruteforce/app/api"
)
type clientAPI struct {
Host string
HTTPClient httpClient
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
func newClientAPI(apiHost string) *clientAPI {
client := &clientAPI{
Host: apiHost,
}
client.HTTPClient = client.createDefaultHTTPClient()
return client
}
func (c *clientAPI) createDefaultHTTPClient() httpClient {
z := &http.Client{
Transport: &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
},
}
return z
}
func (c *clientAPI) getHTTPClient() httpClient {
return c.HTTPClient
}
func (c *clientAPI) setHTTPClient(hc httpClient) {
c.HTTPClient = hc
}
func (c *clientAPI) makeURL(path string) string {
return "http://" + c.Host + path
}
func (c *clientAPI) createPostRequest(reqURL string, params map[string]string) (*http.Request, error) {
data := url.Values{}
for k, v := range params {
data.Set(k, v)
}
req, err := http.NewRequestWithContext(
context.Background(), "POST", reqURL, strings.NewReader(data.Encode()),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req, nil
}
func createGetRequest(reqURL string) (*http.Request, error) {
req, err := http.NewRequestWithContext(context.Background(), "GET", reqURL, nil)
if err != nil {
return nil, err
}
return req, err
}
func (c *clientAPI) extractError(resp *http.Response) (*api.ErrorResponse, error) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
errResp := &api.ErrorResponse{}
err = json.Unmarshal(body, errResp)
if err != nil {
return nil, err
}
return errResp, nil
}