/
http.go
69 lines (56 loc) · 1.66 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
package http
import (
"crypto/tls"
"io"
"net/http"
)
const NO_CONTENT_TYPE string = ""
type HttpRequestEntity struct {
Url string
Username string
Password string
ContentType string
}
type RequestFunc func(HttpRequestEntity, string, io.Reader) (*http.Response, error)
func Request(entity HttpRequestEntity, method string, body io.Reader) (response *http.Response, err error) {
transport := NewRoundTripper()
req, err := http.NewRequest(method, entity.Url, body)
if err != nil {
return
}
req.SetBasicAuth(entity.Username, entity.Password)
if entity.ContentType != NO_CONTENT_TYPE {
req.Header.Add("Content-Type", entity.ContentType)
}
return transport.RoundTrip(req)
}
type RequestAdaptor func() (*http.Response, error)
type HttpGateway interface {
Get(HttpRequestEntity) RequestAdaptor
Post(HttpRequestEntity, io.Reader) RequestAdaptor
Put(HttpRequestEntity, io.Reader) RequestAdaptor
}
func NewHttpGateway() HttpGateway {
return &DefaultHttpGateway{}
}
type DefaultHttpGateway struct{}
func (gateway *DefaultHttpGateway) Get(entity HttpRequestEntity) RequestAdaptor {
return func() (*http.Response, error) {
return Request(entity, "GET", nil)
}
}
func (gateway *DefaultHttpGateway) Post(entity HttpRequestEntity, body io.Reader) RequestAdaptor {
return func() (*http.Response, error) {
return Request(entity, "POST", body)
}
}
func (gateway *DefaultHttpGateway) Put(entity HttpRequestEntity, body io.Reader) RequestAdaptor {
return func() (*http.Response, error) {
return Request(entity, "PUT", body)
}
}
var NewRoundTripper = func() http.RoundTripper {
return &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}