forked from cloudfoundry/cli
/
log_cache_client.go
111 lines (94 loc) · 2.59 KB
/
log_cache_client.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package shared
import (
"fmt"
"net"
"net/http"
"strings"
"time"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/util"
logcache "code.cloudfoundry.org/log-cache/pkg/client"
)
type DebugPrinter struct {
outputs []RequestLoggerOutput
}
func (p DebugPrinter) Print(title, dump string) {
for _, output := range p.outputs {
_ = output.Start() //nolint
_ = output.DisplayType(title, time.Now()) //nolint
_ = output.DisplayDump(dump) //nolint
_ = output.Stop() //nolint
}
}
func (p *DebugPrinter) addOutput(output RequestLoggerOutput) {
p.outputs = append(p.outputs, output)
}
type tokenHTTPClient struct {
c logcache.HTTPClient
accessToken func() string
}
func (c *tokenHTTPClient) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", c.accessToken())
return c.c.Do(req)
}
type httpDebugClient struct {
printer DebugPrinter
c logcache.HTTPClient
}
func (c *httpDebugClient) Do(req *http.Request) (*http.Response, error) {
c.printer.Print("HTTP REQUEST",
fmt.Sprintf("GET %s HTTP/1.1\nHOST: %s://%s\nQUERY: %s\n%s",
req.URL.Path,
req.URL.Scheme,
req.URL.Host,
req.URL.RawQuery,
headersString(req.Header)),
)
resp, err := c.c.Do(req)
if err != nil {
c.printer.Print("HTTP ERROR", err.Error())
return nil, err
}
c.printer.Print("HTTP RESPONSE",
fmt.Sprintf("%s\n%s",
resp.Status,
headersString(resp.Header)),
)
return resp, err
}
// NewLogCacheClient returns back a configured Log Cache Client.
func NewLogCacheClient(logCacheEndpoint string, config command.Config, ui command.UI) *logcache.Client {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: util.NewTLSConfig(nil, config.SkipSSLValidation()),
DialContext: (&net.Dialer{
KeepAlive: 30 * time.Second,
Timeout: config.DialTimeout(),
}).DialContext,
}
var client logcache.HTTPClient //nolint
client = &http.Client{Transport: tr}
verbose, location := config.Verbose()
if verbose {
printer := DebugPrinter{}
printer.addOutput(ui.RequestLoggerTerminalDisplay())
if location != nil {
printer.addOutput(ui.RequestLoggerFileWriter(location))
}
client = &httpDebugClient{printer: printer, c: client}
}
return logcache.NewClient(
logCacheEndpoint,
logcache.WithHTTPClient(&tokenHTTPClient{
c: client,
accessToken: config.AccessToken,
}),
)
}
func headersString(header http.Header) string {
var result string
for name, values := range header {
result += name + ": " + strings.Join(values, ", ") + "\n"
}
return result
}