Skip to content

Commit

Permalink
Merge pull request #20 from marcofranssen/main
Browse files Browse the repository at this point in the history
Print Headers sorted by key
  • Loading branch information
jmalloc authored Jul 7, 2022
2 parents 0836429 + 6d2b109 commit 2355d97
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 2355d97

Please sign in to comment.