/
encoding.go
65 lines (56 loc) · 1.47 KB
/
encoding.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
package mimesniff
import (
"code.google.com/p/go.net/html/charset"
"code.google.com/p/go.text/encoding"
"fmt"
"github.com/marketvibe/chardet"
"os"
"regexp"
"strings"
)
var attrRe *regexp.Regexp
func init() {
attrRe = regexp.MustCompile(`(\w+)="([^"]*)"`)
}
func DetermineEncoding(givenType *ParsedMimeType, head []byte) encoding.Encoding {
// Try to determine encoding ala whatwg "encoding sniffing algorithm"
enc, _, certain := charset.DetermineEncoding(head, givenType.String())
if certain {
return enc
}
// Before doing a byte-level encoding detection, check for xml
// declaration
s := strings.TrimSpace(string(head))
if strings.HasPrefix(s, "<?xml ") {
s = strings.TrimPrefix(s, "<?xml ")
end := strings.Index(s, "?>")
if end > 0 {
s = s[:end]
for _, match := range attrRe.FindAllStringSubmatch(s, -1) {
if match[1] == "encoding" {
if detectedEnc, _ := charset.Lookup(match[2]); detectedEnc != nil {
return detectedEnc
}
}
}
}
}
var detector *chardet.Detector
if givenType.IsHtml() || givenType.IsXml() {
detector = chardet.NewHtmlDetector()
} else {
detector = chardet.NewTextDetector()
}
detected, err := detector.DetectBest(head)
if err != nil {
fmt.Fprintln(os.Stderr, "Error detecting character set, using default.")
return enc
}
if detected.Charset == "GB-18030" {
detected.Charset = "GB18030"
}
if detectedEnc, _ := charset.Lookup(detected.Charset); detectedEnc != nil {
return detectedEnc
}
return enc
}