Extract printing response headers, include status line

This commit is contained in:
Mislav Marohnić 2020-06-08 15:39:35 +02:00
parent fd1e87beeb
commit 4165793fae
2 changed files with 26 additions and 9 deletions

View file

@ -7,6 +7,7 @@ import (
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
@ -100,14 +101,8 @@ func apiRun(opts *ApiOptions) error {
}
if opts.ShowResponseHeaders {
var headerColor, headerColorReset string
if opts.IO.ColorEnabled() {
headerColor = "\x1b[1;34m" // bright blue
headerColorReset = "\x1b[m"
}
for name, vals := range resp.Header {
fmt.Fprintf(opts.IO.Out, "%s%s%s: %s\r\n", headerColor, name, headerColorReset, strings.Join(vals, ", "))
}
fmt.Fprintln(opts.IO.Out, resp.Proto, resp.Status)
printHeaders(opts.IO.Out, resp.Header, opts.IO.ColorEnabled())
fmt.Fprint(opts.IO.Out, "\r\n")
}
@ -138,6 +133,26 @@ func apiRun(opts *ApiOptions) error {
return nil
}
func printHeaders(w io.Writer, headers http.Header, colorize bool) {
var names []string
for name := range headers {
if name == "Status" {
continue
}
names = append(names, name)
}
sort.Strings(names)
var headerColor, headerColorReset string
if colorize {
headerColor = "\x1b[1;34m" // bright blue
headerColorReset = "\x1b[m"
}
for _, name := range names {
fmt.Fprintf(w, "%s%s%s: %s\r\n", headerColor, name, headerColorReset, strings.Join(headers[name], ", "))
}
}
func parseFields(opts *ApiOptions) (map[string]interface{}, error) {
params := make(map[string]interface{})
for _, f := range opts.RawFields {

View file

@ -140,12 +140,14 @@ func Test_apiRun(t *testing.T) {
ShowResponseHeaders: true,
},
httpResponse: &http.Response{
Proto: "HTTP/1.1",
Status: "200 Okey-dokey",
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`body`)),
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
err: nil,
stdout: "Content-Type: text/plain\r\n\r\nbody",
stdout: "HTTP/1.1 200 Okey-dokey\nContent-Type: text/plain\r\n\r\nbody",
stderr: ``,
},
{