-
Notifications
You must be signed in to change notification settings - Fork 1
/
AcceptedMimeType.go
75 lines (57 loc) · 1.37 KB
/
AcceptedMimeType.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
package httphelper
import (
"fmt"
"strings"
mime "github.com/vault-thirteen/auxie/MIME"
"github.com/vault-thirteen/auxie/number"
)
type AcceptedMimeType struct {
MimeType string
Weight float32
}
func ParseRecord(rec string) (amt *AcceptedMimeType, err error) {
parts := strings.Split(strings.TrimSpace(rec), ";")
if len(parts) == 0 {
return nil, fmt.Errorf(ErrSyntaxErrorInRecord, strings.TrimSpace(rec))
}
if len(parts[0]) == 0 {
return nil, fmt.Errorf(ErrSyntaxErrorInRecord, strings.TrimSpace(rec))
}
err = checkMimeType(parts[0])
if err != nil {
return nil, err
}
amt = &AcceptedMimeType{
MimeType: parts[0],
}
switch len(parts) {
case 1:
// Example: `text/html`.
amt.Weight = 1.0
return amt, nil
case 2:
// Example: `application/xml;q=0.9`.
amt.Weight, err = ParseRecordWeight(parts[1])
if err != nil {
return nil, err
}
return amt, nil
default:
return nil, fmt.Errorf(ErrSyntaxErrorInRecord, strings.TrimSpace(rec))
}
}
func ParseRecordWeight(rwt string) (weight float32, err error) {
// Example: `q=0.9`.
parts := strings.Split(strings.TrimSpace(rwt), "=")
if (len(parts) != 2) || (parts[0] != `q`) {
return 0, fmt.Errorf(ErrSyntaxErrorInWeight, rwt)
}
return number.ParseFloat32(parts[1])
}
func checkMimeType(mt string) (err error) {
_, _, err = mime.GetMimeTypeParts(mt)
if err != nil {
return err
}
return nil
}