Skip to content

Commit 758784a

Browse files
committed
chore: improve Error.HeaderToString and cover with test.
1 parent a83a386 commit 758784a

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

api/http/error.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,16 @@ func (e *Error) HeaderToString(selected []string) string {
4646
headerString := ""
4747
if len(selected) == 0 {
4848
for key := range e.Header {
49-
headerString += fmt.Sprintf("%s: %s\r\n", key, e.Header[key])
49+
headerString += fmt.Sprintf("%s: %s\r\n",
50+
http.CanonicalHeaderKey(key),
51+
e.Header.Get(key))
5052
}
5153
} else {
5254
for _, candidate := range selected {
5355
if e.Header.Get(candidate) != "" {
54-
headerString += fmt.Sprintf("%s: %s\n", candidate, e.Header.Get(candidate))
56+
headerString += fmt.Sprintf("%s: %s\n",
57+
http.CanonicalHeaderKey(candidate),
58+
e.Header.Get(candidate))
5559
}
5660
}
5761
}

api/write_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,44 @@ func TestWriteApiErrorHeaders(t *testing.T) {
312312
wg.Wait()
313313
assert.Equal(t, calls, 3)
314314
}
315+
316+
func TestWriteErrorHeaderToString(t *testing.T) {
317+
header := ihttp.Header{
318+
"Date": []string{"2024-08-07T12:00:00.009"},
319+
"Content-Length": []string{"12"},
320+
"Content-Type": []string{"application/json", "encoding UTF-8"},
321+
"X-Test-Value1": []string{"SaturnV"},
322+
"X-Test-Value2": []string{"Apollo11"},
323+
"Retry-After": []string{"2044"},
324+
"Trace-Id": []string{"123456789ABCDEF0"},
325+
}
326+
327+
err := http.Error{
328+
StatusCode: ihttp.StatusBadRequest,
329+
Code: "bad request",
330+
Message: "this is just a test",
331+
Err: nil,
332+
RetryAfter: 2044,
333+
Header: header,
334+
}
335+
336+
fullString := err.HeaderToString([]string{})
337+
338+
// write order is not guaranteed
339+
assert.Contains(t, fullString, "Date: 2024-08-07T12:00:00.009")
340+
assert.Contains(t, fullString, "Content-Length: 12")
341+
assert.Contains(t, fullString, "Content-Type: application/json")
342+
assert.Contains(t, fullString, "X-Test-Value1: SaturnV")
343+
assert.Contains(t, fullString, "X-Test-Value2: Apollo11")
344+
assert.Contains(t, fullString, "Retry-After: 2044")
345+
assert.Contains(t, fullString, "Trace-Id: 123456789ABCDEF0")
346+
347+
filterString := err.HeaderToString([]string{"date", "trace-id", "x-test-value1", "x-test-value2"})
348+
349+
// write order will follow filter arguments
350+
assert.Equal(t, filterString,
351+
"Date: 2024-08-07T12:00:00.009\nTrace-Id: 123456789ABCDEF0\nX-Test-Value1: SaturnV\nX-Test-Value2: Apollo11\n",
352+
)
353+
assert.NotContains(t, filterString, "Content-Type: application/json")
354+
assert.NotContains(t, filterString, "Retry-After: 2044")
355+
}

0 commit comments

Comments
 (0)