/
http.go
91 lines (79 loc) · 2.03 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
package roundtrip
import (
"bytes"
"fmt"
"io"
"net/http"
"github.com/caicloud/aloe/runtime"
)
// Clientset defines a clientset to do http request
type Clientset interface {
// DoRequest read round trip config and return response of request
DoRequest(rt *runtime.RoundTrip) (*http.Response, error)
// Set sets custom client with name
// client with empty name will be default client
Set(name string, c *http.Client)
// Get get custom client with name
Get(name string) (*http.Client, bool)
}
// clientset defines multiple clients
type clientset struct {
defaultClient *http.Client
namedClients map[string]*http.Client
}
// NewClientset returns a clientset for roundtrip
func NewClientset(c *http.Client) Clientset {
cs := &clientset{
defaultClient: c,
namedClients: map[string]*http.Client{},
}
if cs.defaultClient == nil {
cs.defaultClient = http.DefaultClient
}
return cs
}
// Set implements Clientset interface
func (cs *clientset) Set(name string, c *http.Client) {
if name == "" {
cs.defaultClient = c
return
}
cs.namedClients[name] = c
}
// Get implements Clientset interface
func (cs *clientset) Get(name string) (*http.Client, bool) {
if name == "" {
return cs.defaultClient, true
}
c, ok := cs.namedClients[name]
return c, ok
}
// DoRequest implements Clientset interface
func (cs *clientset) DoRequest(rt *runtime.RoundTrip) (*http.Response, error) {
c, ok := cs.Get(rt.Client)
if !ok {
return nil, fmt.Errorf("can't find client with name %s", rt.Client)
}
return doRequest(c, &rt.Request)
}
func doRequest(c *http.Client, reqConf *runtime.Request) (*http.Response, error) {
var body io.Reader
if reqConf.Body != nil {
body = bytes.NewBuffer(reqConf.Body)
}
req, err := http.NewRequest(reqConf.Method, getURL(reqConf), body)
if err != nil {
return nil, err
}
for k, v := range reqConf.Headers {
req.Header.Set(k, v)
}
return c.Do(req)
}
func getURL(req *runtime.Request) string {
scheme := "http://"
if req.Scheme != "" {
scheme = req.Scheme + "://"
}
return scheme + req.Host + req.Path
}