-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader.go
More file actions
77 lines (66 loc) · 1.59 KB
/
header.go
File metadata and controls
77 lines (66 loc) · 1.59 KB
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
package wo
import (
"net/http"
"strings"
)
func SetHeaderIfMissing(res http.ResponseWriter, key string, value string) {
if res.Header().Get(key) == "" {
res.Header().Set(key, value)
}
}
func ParseAcceptLanguageHeader(languageHeader string) []string {
if languageHeader == "" {
return make([]string, 0)
}
options := strings.Split(languageHeader, ",")
l := len(options)
languages := make([]string, l)
for i := 0; i < l; i++ {
locale := strings.SplitN(options[i], ";", 2)
languages[i] = strings.Trim(locale[0], " ")
}
return languages
}
func ParseAcceptHeader(acceptHeader string) []string {
if acceptHeader == "" {
return make([]string, 0)
}
parts := strings.Split(acceptHeader, ",")
out := make([]string, 0, len(parts))
for _, part := range parts {
if i := strings.IndexByte(part, ';'); i > 0 {
part = part[:i]
}
if part = strings.TrimSpace(part); part != "" {
out = append(out, part)
}
}
return out
}
func NegotiateFormat(accepted []string, offered ...string) string {
if len(offered) == 0 {
panic("negotiateFormat: you must provide at least one offer")
}
if len(accepted) == 0 {
return offered[0]
}
for _, a := range accepted {
for _, offer := range offered {
// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,
// therefore we can just iterate over the string without casting it into []rune
i := 0
for ; i < len(a) && i < len(offer); i++ {
if a[i] == '*' || offer[i] == '*' {
return offer
}
if a[i] != offer[i] {
break
}
}
if i == len(a) {
return offer
}
}
}
return ""
}