| 1 | package utils |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/stretchr/testify/require" |
| 8 | ) |
| 9 | |
| 10 | func headerKeySamples() []string { |
| 11 | return []string{ |
| 12 | "", |
| 13 | "Content-Type", |
| 14 | "content-type", |
| 15 | "CONTENT-TYPE", |
| 16 | "cOnTeNt-TyPe", |
| 17 | "Host", |
| 18 | "host", |
| 19 | "x-request-id", |
| 20 | "X-Request-ID", |
| 21 | "x--double-dash", |
| 22 | "-leading-dash", |
| 23 | "trailing-dash-", |
| 24 | "1-2-3", |
| 25 | "etag", |
| 26 | "WWW-Authenticate", |
| 27 | "www-authenticate", |
| 28 | "Header With Space", |
| 29 | "Bad:Colon", |
| 30 | "Tab\tKey", |
| 31 | "non-ascii-é", |
| 32 | "under_score", |
| 33 | "tilde~ok", |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func Test_CanonicalHeaderKey(t *testing.T) { |
| 38 | t.Parallel() |
| 39 | for _, in := range headerKeySamples() { |
| 40 | want := http.CanonicalHeaderKey(in) |
| 41 | require.Equal(t, want, CanonicalHeaderKey(in), "input %q", in) |
| 42 | require.Equal(t, want, string(CanonicalHeaderKey([]byte(in))), "input %q", in) |
| 43 | } |
| 44 | |
| 45 | // Already-canonical and invalid keys come back without copying: for |
| 46 | // []byte inputs the same backing array is returned. |
| 47 | for _, in := range []string{"Content-Type", "Bad Key", "X-Id"} { |
| 48 | b := []byte(in) |
| 49 | out := CanonicalHeaderKey(b) |
| 50 | require.Same(t, &b[0], &out[0], "input %q must not copy", in) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func Benchmark_CanonicalHeaderKey(b *testing.B) { |
| 55 | inputs := []struct { |
| 56 | name string |
| 57 | value string |
| 58 | }{ |
| 59 | {"canonical", "Content-Type"}, |
| 60 | {"common-lower", "content-type"}, |
| 61 | {"custom-lower", "x-custom-request-id"}, |
| 62 | } |
| 63 | for _, input := range inputs { |
| 64 | b.Run(input.name+"/fiber", func(b *testing.B) { |
| 65 | b.ReportAllocs() |
| 66 | for b.Loop() { |
| 67 | CanonicalHeaderKey(input.value) |
| 68 | } |
| 69 | }) |
| 70 | b.Run(input.name+"/default", func(b *testing.B) { |
| 71 | b.ReportAllocs() |
| 72 | for b.Loop() { |
| 73 | http.CanonicalHeaderKey(input.value) |
| 74 | } |
| 75 | }) |
| 76 | } |
| 77 | } |