-
Notifications
You must be signed in to change notification settings - Fork 56
/
acceptItem.go
64 lines (54 loc) · 1.32 KB
/
acceptItem.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
package acceptHeaders
import (
"strconv"
"strings"
)
const qualitySign = ";q="
const defaultQuality = 1000
const maxQualityDigits = 3
type acceptItem struct {
value string
quality int
}
func parseAcceptItem(input string) acceptItem {
indexQSign := strings.Index(input, qualitySign)
if indexQSign < 0 {
return acceptItem{input, defaultQuality}
}
value := input[:indexQSign]
strQuality := input[indexQSign+len(qualitySign):]
if semiColonIndex := strings.IndexByte(strQuality, ';'); semiColonIndex >= 0 {
strQuality = strQuality[:semiColonIndex]
}
strQualityLen := len(strQuality)
if strQualityLen == 0 {
return acceptItem{value, defaultQuality}
}
if strQualityLen > 1 && strQuality[1] != '.' {
return acceptItem{value, defaultQuality}
}
// "q=1" or q is an invalid value
if strQuality[0] != '0' {
return acceptItem{value, defaultQuality}
}
// "q=0."
if strQualityLen <= 2 {
return acceptItem{value, 0}
}
strRest := strQuality[2:]
strRestLen := len(strRest)
if strRestLen > maxQualityDigits {
strRestLen = maxQualityDigits
strRest = strRest[:strRestLen]
}
quality, err := strconv.Atoi(strRest)
if err != nil {
quality = defaultQuality
} else {
missingDigits := maxQualityDigits - strRestLen
for i := 0; i < missingDigits; i++ {
quality *= 10
}
}
return acceptItem{value, quality}
}