-
Notifications
You must be signed in to change notification settings - Fork 95
/
cleanup.go
95 lines (83 loc) · 1.75 KB
/
cleanup.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
package formatter
import (
"bytes"
"io"
)
// HeaderCleaner removes > and < from curl --verbose output.
type HeaderCleaner struct {
Out io.Writer
// Verbose removes the request headers part of the output as well as the lines
// starting with * if set to false.
Verbose bool
// Post is inserted after the request headers.
Post *bytes.Buffer
HeadersDone chan<- struct{}
buf []byte
line []byte
}
var (
capath = []byte(" CApath:")
ccapath = []byte("* CApath:")
)
func (c *HeaderCleaner) Write(p []byte) (n int, err error) {
n = len(p)
cp := c.buf
p = bytes.Replace(p, capath, ccapath, 1) // Fix curl misformatted line
closeAfterWrite := false
for len(p) > 0 {
idx := bytes.IndexByte(p, '\n')
if idx == -1 {
c.line = append(c.line, p...)
break
}
c.line = append(c.line, p[:idx+1]...)
p = p[idx+1:]
ignore := false
b, i := firstVisibleChar(c.line)
switch b {
case '>':
if c.Verbose {
c.line = c.line[i+2:]
} else {
ignore = true
}
case '<':
c.line = c.line[i+2:]
if bytes.Equal(c.line, []byte("\r\n")) && c.HeadersDone != nil {
closeAfterWrite = true
}
case '}', '{':
ignore = true
if c.Verbose && c.Post != nil {
cp = append(append(cp, bytes.TrimSpace(c.Post.Bytes())...), '\n', '\n')
c.Post = nil
}
case '*':
if !c.Verbose {
ignore = true
}
}
if !ignore {
cp = append(cp, c.line...)
}
c.line = c.line[:0]
}
_, err = c.Out.Write(cp)
if closeAfterWrite {
close(c.HeadersDone)
}
return
}
var colorEscape = []byte("\x1b[")
func firstVisibleChar(b []byte) (byte, int) {
if bytes.HasPrefix(b, colorEscape) {
if idx := bytes.IndexByte(b, 'm'); idx != -1 {
if idx < len(b) {
return b[idx+1], idx + 1
} else {
return 0, -1
}
}
}
return b[0], 0
}