Debian Codegraph @

headerkey.go

raw
1 package utils
2
3 import (
4 "github.com/gofiber/utils/v2/internal/caseconv"
5 "github.com/gofiber/utils/v2/internal/unsafeconv"
6 )
7
8 // headerTokenTable flags the bytes valid in an HTTP header field name — the
9 // RFC 9110 token alphabet, matching net/http's validHeaderFieldByte.
10 var headerTokenTable = buildHeaderTokenTable()
11
12 func buildHeaderTokenTable() [256]bool {
13 var t [256]bool
14 for c := byte('0'); c <= '9'; c++ {
15 t[c] = true
16 }
17 for c := byte('a'); c <= 'z'; c++ {
18 t[c] = true
19 }
20 for c := byte('A'); c <= 'Z'; c++ {
21 t[c] = true
22 }
23 for _, c := range []byte("!#$%&'*+-.^_`|~") {
24 t[c] = true
25 }
26 return t
27 }
28
29 // CanonicalHeaderKey returns the canonical form of the HTTP header key:
30 // the first letter and any letter following a hyphen upper-cased, the rest
31 // lower-cased. The output matches net/http.CanonicalHeaderKey byte for
32 // byte, including its guard: a key containing any byte outside the header
33 // token alphabet is returned unchanged. Unlike the stdlib it accepts byte
34 // slices as well as strings and allocates only when the key actually needs
35 // rewriting — already-canonical keys, the overwhelmingly common case on
36 // receive paths, are validated in one table pass and returned as-is
37 // without the stdlib's canonical-key cache lookup.
38 func CanonicalHeaderKey[S byteSeq](key S) S {
39 upper := true
40 fix := -1
41 for i := 0; i < len(key); i++ {
42 c := key[i]
43 if !headerTokenTable[c] {
44 return key
45 }
46 if fix < 0 && (upper && 'a' <= c && c <= 'z' || !upper && 'A' <= c && c <= 'Z') {
47 fix = i
48 }
49 upper = c == '-'
50 }
51 if fix < 0 {
52 return key
53 }
54
55 buf := make([]byte, len(key))
56 copy(buf, unsafeconv.Bytes(key))
57 upper = fix == 0 || buf[fix-1] == '-'
58 for i := fix; i < len(buf); i++ {
59 c := buf[i]
60 if upper {
61 c = caseconv.ToUpperTable[c]
62 } else {
63 c = caseconv.ToLowerTable[c]
64 }
65 buf[i] = c
66 upper = c == '-'
67 }
68 // The zero-copy view is sound: buf is uniquely owned here and is never
69 // written again, which is what the string instantiation requires.
70 return unsafeconv.Seq[S](buf)
71 }