-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
key.go
81 lines (64 loc) · 1.66 KB
/
key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package httpsfv
import (
"errors"
"fmt"
"io"
)
// ErrInvalidKeyFormat is returned when the format of a parameter or dictionary key is invalid.
var ErrInvalidKeyFormat = errors.New("invalid key format")
// isKeyChar checks if c is a valid key characters.
func isKeyChar(c byte) bool {
if isLowerCaseAlpha(c) || isDigit(c) {
return true
}
switch c {
case '_', '-', '.', '*':
return true
}
return false
}
// checkKey checks if the given value is a valid parameter key according to
// https://httpwg.org/specs/rfc8941.html#param.
func checkKey(k string) error {
if len(k) == 0 {
return fmt.Errorf("a key cannot be empty: %w", ErrInvalidKeyFormat)
}
if !isLowerCaseAlpha(k[0]) && k[0] != '*' {
return fmt.Errorf("a key must start with a lower case alpha character or *: %w", ErrInvalidKeyFormat)
}
for i := 1; i < len(k); i++ {
if !isKeyChar(k[i]) {
return fmt.Errorf("the character %c isn't allowed in a key: %w", k[i], ErrInvalidKeyFormat)
}
}
return nil
}
// marshalKey serializes as defined in
// https://httpwg.org/specs/rfc8941.html#ser-key.
func marshalKey(b io.StringWriter, k string) error {
if err := checkKey(k); err != nil {
return err
}
_, err := b.WriteString(k)
return err
}
// parseKey parses as defined in
// https://httpwg.org/specs/rfc8941.html#parse-key.
func parseKey(s *scanner) (string, error) {
if s.eof() {
return "", &UnmarshalError{s.off, ErrInvalidKeyFormat}
}
c := s.data[s.off]
if !isLowerCaseAlpha(c) && c != '*' {
return "", &UnmarshalError{s.off, ErrInvalidKeyFormat}
}
start := s.off
s.off++
for !s.eof() {
if !isKeyChar(s.data[s.off]) {
break
}
s.off++
}
return s.data[start:s.off], nil
}