forked from cloudfoundry/go-uaa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
curl.go
73 lines (62 loc) · 1.52 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
package uaa
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/textproto"
"strings"
)
// Curl makes a request to the UAA API with the given path, method, data, and
// headers.
func (a *API) Curl(path string, method string, data string, headers []string) (string, string, error) {
u := urlWithPath(*a.TargetURL, path)
req, err := http.NewRequest(method, u.String(), strings.NewReader(data))
if err != nil {
return "", "", err
}
err = mergeHeaders(req.Header, strings.Join(headers, "\n"))
if err != nil {
return "", "", err
}
if a.Verbose {
logRequest(req)
}
a.ensureTransport(a.AuthenticatedClient)
resp, err := a.AuthenticatedClient.Do(req)
if err != nil {
if a.Verbose {
fmt.Printf("%v\n\n", err)
}
return "", "", err
}
defer resp.Body.Close()
headerBytes, _ := httputil.DumpResponse(resp, false)
resHeaders := string(headerBytes)
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil && a.Verbose {
fmt.Printf("%v\n\n", err)
}
resBody := string(bytes)
if a.Verbose {
logResponse(resp)
}
return resHeaders, resBody, nil
}
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
}