-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
69 lines (53 loc) · 1.46 KB
/
http.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
// Package translation provides a helper function for parsing the HTTP Accept-Language header
package translation
import (
"sort"
"strconv"
"strings"
)
type AcceptLanguage struct {
Lang string // de-AT, de
Base string // de, de
Region string // AT, ""
Quality float64
}
// ParseAcceptLanguage parses an Accept-Language header into a slice of AcceptLanguage, sorted by quality in descending order.
func ParseAcceptLanguage(headerLine string) []AcceptLanguage {
ret := make([]AcceptLanguage, 0)
for _, lq := range strings.Split(headerLine, ",") {
lq = strings.Trim(lq, " ")
langQuality := strings.SplitN(lq, ";", 2)
if langQuality[0] == "" {
continue
}
al := AcceptLanguage{Lang: langQuality[0]}
langRegion := strings.Split(al.Lang, "-")
al.Base = langRegion[0]
if len(langRegion) > 1 {
al.Region = langRegion[1]
}
quality := "1"
if len(langQuality) > 1 {
qVal := strings.Split(langQuality[1], "=")
if len(qVal) < 2 {
quality = "0"
} else {
quality = strings.Trim(qVal[1], " ")
}
}
qFloat, err := strconv.ParseFloat(quality, 64)
if err != nil {
qFloat = 0
}
al.Quality = qFloat
ret = append(ret, al)
}
sort.Slice(ret, func(i, j int) bool {
return ret[i].Quality > ret[j].Quality
})
return ret
}
// GetBaseLanguage extracts the base language from the given AcceptLanguage parameter.
func GetBaseLanguage(acceptLanguage AcceptLanguage) string {
return strings.Split(acceptLanguage.Lang, "-")[0]
}