forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
curl.go
87 lines (70 loc) · 2 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
85
86
87
package api
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/textproto"
"strings"
"github.com/cloudfoundry/cli/cf/configuration"
"github.com/cloudfoundry/cli/cf/errors"
. "github.com/cloudfoundry/cli/cf/i18n"
"github.com/cloudfoundry/cli/cf/net"
)
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(T("Error parsing headers"), err)
return
}
res, err := repo.gateway.PerformRequest(req)
if _, ok := err.(errors.HttpError); ok {
err = nil
}
if err != nil {
return
}
defer res.Body.Close()
headerBytes, _ := httputil.DumpResponse(res, false)
resHeaders = string(headerBytes)
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
err = errors.NewWithError(T("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
}