forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
curl.go
84 lines (68 loc) · 1.84 KB
/
curl.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
package api
import (
"bufio"
"cf/configuration"
"cf/errors"
"cf/net"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/textproto"
"strings"
)
type CurlRepository interface {
Request(method, path, header, body string) (resHeaders, resBody string, apiErr error)
}
type CloudControllerCurlRepository struct {
config configuration.Reader
gateway net.Gateway
}
func NewCloudControllerCurlRepository(config configuration.Reader, gateway net.Gateway) (repo CloudControllerCurlRepository) {
repo.config = config
repo.gateway = gateway
return
}
func (repo CloudControllerCurlRepository) Request(method, path, headerString, body string) (resHeaders, resBody string, err error) {
url := fmt.Sprintf("%s/%s", repo.config.ApiEndpoint(), strings.TrimLeft(path, "/"))
req, err := repo.gateway.NewRequest(method, url, repo.config.AccessToken(), strings.NewReader(body))
if err != nil {
return
}
err = mergeHeaders(req.HttpReq.Header, headerString)
if err != nil {
err = errors.NewWithError("Error parsing headers", err)
return
}
res, err := repo.gateway.PerformRequest(req)
if _, ok := err.(errors.HttpError); ok {
err = nil
}
if err != nil {
return
}
headerBytes, _ := httputil.DumpResponse(res, false)
resHeaders = string(headerBytes)
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
err = errors.NewWithError("Error reading response", err)
}
resBody = string(bytes)
return
}
func mergeHeaders(destination http.Header, headerString string) (err error) {
headerString = strings.TrimSpace(headerString)
headerString += "\n\n"
headerReader := bufio.NewReader(strings.NewReader(headerString))
headers, err := textproto.NewReader(headerReader).ReadMIMEHeader()
if err != nil {
return
}
for key, values := range headers {
destination.Del(key)
for _, value := range values {
destination.Add(key, value)
}
}
return
}