/
logger.go
104 lines (84 loc) · 2.47 KB
/
logger.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package httputil
import (
"errors"
"net/http"
"net/http/httputil"
"os"
"strconv"
"github.com/snapcore/snapd/logger"
)
type debugflag uint
// set these via the Key environ
const (
DebugRequest = debugflag(1 << iota)
DebugResponse
DebugBody
)
func (f debugflag) debugRequest() bool {
return f&DebugRequest != 0
}
func (f debugflag) debugResponse() bool {
return f&DebugResponse != 0
}
func (f debugflag) debugBody() bool {
return f&DebugBody != 0
}
// LoggedTransport is an http.RoundTripper that can be used by
// http.Client to log request/response roundtrips.
type LoggedTransport struct {
Transport http.RoundTripper
Key string
body bool
}
// RoundTrip is from the http.RoundTripper interface.
func (tr *LoggedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
flags := tr.getFlags()
if flags.debugRequest() {
buf, _ := httputil.DumpRequestOut(req, tr.body && flags.debugBody())
logger.Debugf("> %q", buf)
}
rsp, err := tr.Transport.RoundTrip(req)
if err == nil && flags.debugResponse() {
buf, _ := httputil.DumpResponse(rsp, tr.body && flags.debugBody())
logger.Debugf("< %q", buf)
}
return rsp, err
}
func (tr *LoggedTransport) getFlags() debugflag {
flags, err := strconv.Atoi(os.Getenv(tr.Key))
if err != nil {
flags = 0
}
return debugflag(flags)
}
func checkRedirect(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return errors.New("stopped after 10 redirects")
}
return nil
}
// BaseTransport returns the underlying http.Transport of a client created with NewHTTPClient. It panics if that's not the case. For tests.
func BaseTransport(cli *http.Client) *http.Transport {
tr, ok := cli.Transport.(*LoggedTransport)
if !ok {
panic("client must have been created with httputil.NewHTTPClient")
}
return tr.Transport.(*http.Transport)
}