Skip to content

Commit

Permalink
chore: improve Error.HeaderToString and cover with test.
Browse files Browse the repository at this point in the history
  • Loading branch information
karel-rehor committed Aug 7, 2024
1 parent a83a386 commit 758784a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
8 changes: 6 additions & 2 deletions api/http/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,16 @@ func (e *Error) HeaderToString(selected []string) string {
headerString := ""
if len(selected) == 0 {
for key := range e.Header {
headerString += fmt.Sprintf("%s: %s\r\n", key, e.Header[key])
headerString += fmt.Sprintf("%s: %s\r\n",
http.CanonicalHeaderKey(key),
e.Header.Get(key))
}
} else {
for _, candidate := range selected {
if e.Header.Get(candidate) != "" {
headerString += fmt.Sprintf("%s: %s\n", candidate, e.Header.Get(candidate))
headerString += fmt.Sprintf("%s: %s\n",
http.CanonicalHeaderKey(candidate),
e.Header.Get(candidate))
}
}
}
Expand Down
41 changes: 41 additions & 0 deletions api/write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,44 @@ func TestWriteApiErrorHeaders(t *testing.T) {
wg.Wait()
assert.Equal(t, calls, 3)
}

func TestWriteErrorHeaderToString(t *testing.T) {
header := ihttp.Header{
"Date": []string{"2024-08-07T12:00:00.009"},
"Content-Length": []string{"12"},
"Content-Type": []string{"application/json", "encoding UTF-8"},
"X-Test-Value1": []string{"SaturnV"},
"X-Test-Value2": []string{"Apollo11"},
"Retry-After": []string{"2044"},
"Trace-Id": []string{"123456789ABCDEF0"},
}

err := http.Error{
StatusCode: ihttp.StatusBadRequest,
Code: "bad request",
Message: "this is just a test",
Err: nil,
RetryAfter: 2044,
Header: header,
}

fullString := err.HeaderToString([]string{})

// write order is not guaranteed
assert.Contains(t, fullString, "Date: 2024-08-07T12:00:00.009")
assert.Contains(t, fullString, "Content-Length: 12")
assert.Contains(t, fullString, "Content-Type: application/json")
assert.Contains(t, fullString, "X-Test-Value1: SaturnV")
assert.Contains(t, fullString, "X-Test-Value2: Apollo11")
assert.Contains(t, fullString, "Retry-After: 2044")
assert.Contains(t, fullString, "Trace-Id: 123456789ABCDEF0")

filterString := err.HeaderToString([]string{"date", "trace-id", "x-test-value1", "x-test-value2"})

// write order will follow filter arguments
assert.Equal(t, filterString,
"Date: 2024-08-07T12:00:00.009\nTrace-Id: 123456789ABCDEF0\nX-Test-Value1: SaturnV\nX-Test-Value2: Apollo11\n",
)
assert.NotContains(t, filterString, "Content-Type: application/json")
assert.NotContains(t, filterString, "Retry-After: 2044")
}

0 comments on commit 758784a

Please sign in to comment.