Skip to content

Commit

Permalink
fix headers/body order (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusz834 committed May 8, 2023
1 parent 571cdca commit e63e657
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
11 changes: 11 additions & 0 deletions formatter/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ type HeaderCleaner struct {
// Post is inserted after the request headers.
Post *bytes.Buffer

HeadersDone chan<- struct{}

buf []byte
line []byte
}
Expand All @@ -29,6 +31,8 @@ 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 {
Expand All @@ -48,6 +52,9 @@ func (c *HeaderCleaner) Write(p []byte) (n int, err error) {
}
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 {
Expand All @@ -62,9 +69,13 @@ func (c *HeaderCleaner) Write(p []byte) (n int, err error) {
if !ignore {
cp = append(cp, c.line...)
}

c.line = c.line[:0]
}
_, err = c.Out.Write(cp)
if closeAfterWrite {
close(c.HeadersDone)
}
return
}

Expand Down
26 changes: 25 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,28 @@ func main() {
fmt.Println()
return
}

cmd := exec.Command("curl", opts...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = &formatter.HeaderCleaner{

tmpOut := &formatter.HeaderCleaner{
Out: stderr,
Verbose: verbose,
Post: input,
}

if terminal.IsTerminal(stdoutFd) && terminal.IsTerminal(stderrFd) && !quiet {
headerBlock := make(chan struct{})
cmd.Stdout = &blockedWrite{
ch: headerBlock,
out: stdout,
}
tmpOut.HeadersDone = headerBlock
}

cmd.Stderr = tmpOut

if (opts.Has("I") || opts.Has("head")) && terminal.IsTerminal(stdoutFd) {
cmd.Stdout = ioutil.Discard
}
Expand Down Expand Up @@ -175,3 +189,13 @@ func headerSupplied(opts args.Opts, header string) bool {
}
return false
}

type blockedWrite struct {
ch <-chan struct{}
out io.Writer
}

func (c *blockedWrite) Write(p []byte) (n int, err error) {
<-c.ch
return c.out.Write(p)
}

0 comments on commit e63e657

Please sign in to comment.