Skip to content

Commit

Permalink
Print Headers sorted by key
Browse files Browse the repository at this point in the history
Signed-off-by: Marco Franssen <marco.franssen@gmail.com>
  • Loading branch information
marcofranssen committed Jul 7, 2022
1 parent 0836429 commit 6d2b109
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions cmd/echo-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io/ioutil"
"net/http"
"os"
"sort"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -54,10 +55,7 @@ func handler(wr http.ResponseWriter, req *http.Request) {

if os.Getenv("LOG_HTTP_HEADERS") != "" {
fmt.Printf("Headers\n")
//Iterate over all header fields
for k, v := range req.Header {
fmt.Printf("%q : %q\n", k, v)
}
printHeaders(os.Stdout, req.Header)
}

if os.Getenv("LOG_HTTP_BODY") != "" {
Expand Down Expand Up @@ -257,11 +255,7 @@ func writeRequest(w io.Writer, req *http.Request) {
fmt.Fprintln(w, "")

fmt.Fprintf(w, "Host: %s\n", req.Host)
for key, values := range req.Header {
for _, value := range values {
fmt.Fprintf(w, "%s: %s\n", key, value)
}
}
printHeaders(w, req.Header)

var body bytes.Buffer
io.Copy(&body, req.Body) // nolint:errcheck
Expand All @@ -271,3 +265,17 @@ func writeRequest(w io.Writer, req *http.Request) {
body.WriteTo(w) // nolint:errcheck
}
}

func printHeaders(w io.Writer, h http.Header) {
sortedKeys := make([]string, len(h))

for key := range h {
sortedKeys = append(sortedKeys, key)
}

sort.Strings(sortedKeys)

for _, key := range sortedKeys {
fmt.Fprintf(w, "%s: %s\n", key, h.Get(key))
}
}

0 comments on commit 6d2b109

Please sign in to comment.