1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package charset provides common text encodings for HTML documents.
7 // The mapping from encoding labels to encodings is defined at
8 // https://encoding.spec.whatwg.org/.
9 package charset // import "golang.org/x/net/html/charset"
19 "golang.org/x/net/html"
20 "golang.org/x/text/encoding"
21 "golang.org/x/text/encoding/charmap"
22 "golang.org/x/text/encoding/htmlindex"
23 "golang.org/x/text/transform"
26 // Lookup returns the encoding with the specified label, and its canonical
27 // name. It returns nil and the empty string if label is not one of the
28 // standard encodings for HTML. Matching is case-insensitive and ignores
29 // leading and trailing whitespace. Encoders will use HTML escape sequences for
30 // runes that are not supported by the character set.
31 func Lookup(label string) (e encoding.Encoding, name string) {
32 e, err := htmlindex.Get(label)
36 name, _ = htmlindex.Name(e)
37 return &htmlEncoding{e}, name
40 type htmlEncoding struct{ encoding.Encoding }
42 func (h *htmlEncoding) NewEncoder() *encoding.Encoder {
43 // HTML requires a non-terminating legacy encoder. We use HTML escapes to
44 // substitute unsupported code points.
45 return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder())
48 // DetermineEncoding determines the encoding of an HTML document by examining
49 // up to the first 1024 bytes of content and the declared Content-Type.
51 // See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding
52 func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) {
53 if len(content) > 1024 {
54 content = content[:1024]
57 for _, b := range boms {
58 if bytes.HasPrefix(content, b.bom) {
59 e, name = Lookup(b.enc)
64 if _, params, err := mime.ParseMediaType(contentType); err == nil {
65 if cs, ok := params["charset"]; ok {
66 if e, name = Lookup(cs); e != nil {
73 e, name = prescan(content)
79 // Try to detect UTF-8.
80 // First eliminate any partial rune at the end.
81 for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {
86 if utf8.RuneStart(b) {
92 for _, c := range content {
98 if hasHighBit && utf8.Valid(content) {
99 return encoding.Nop, "utf-8", false
102 // TODO: change default depending on user's locale?
103 return charmap.Windows1252, "windows-1252", false
106 // NewReader returns an io.Reader that converts the content of r to UTF-8.
107 // It calls DetermineEncoding to find out what r's encoding is.
108 func NewReader(r io.Reader, contentType string) (io.Reader, error) {
109 preview := make([]byte, 1024)
110 n, err := io.ReadFull(r, preview)
112 case err == io.ErrUnexpectedEOF:
113 preview = preview[:n]
114 r = bytes.NewReader(preview)
118 r = io.MultiReader(bytes.NewReader(preview), r)
121 if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop {
122 r = transform.NewReader(r, e.NewDecoder())
127 // NewReaderLabel returns a reader that converts from the specified charset to
128 // UTF-8. It uses Lookup to find the encoding that corresponds to label, and
129 // returns an error if Lookup returns nil. It is suitable for use as
130 // encoding/xml.Decoder's CharsetReader function.
131 func NewReaderLabel(label string, input io.Reader) (io.Reader, error) {
132 e, _ := Lookup(label)
134 return nil, fmt.Errorf("unsupported charset: %q", label)
136 return transform.NewReader(input, e.NewDecoder()), nil
139 func prescan(content []byte) (e encoding.Encoding, name string) {
140 z := html.NewTokenizer(bytes.NewReader(content))
143 case html.ErrorToken:
146 case html.StartTagToken, html.SelfClosingTagToken:
147 tagName, hasAttr := z.TagName()
148 if !bytes.Equal(tagName, []byte("meta")) {
151 attrList := make(map[string]bool)
159 needPragma := dontKnow
165 key, val, hasAttr = z.TagAttr()
171 for i, c := range val {
172 if 'A' <= c && c <= 'Z' {
179 if bytes.Equal(val, []byte("content-type")) {
185 name = fromMetaElement(string(val))
187 e, name = Lookup(name)
189 needPragma = doNeedPragma
195 e, name = Lookup(string(val))
196 needPragma = doNotNeedPragma
200 if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
204 if strings.HasPrefix(name, "utf-16") {
216 func fromMetaElement(s string) string {
218 csLoc := strings.Index(s, "charset")
222 s = s[csLoc+len("charset"):]
223 s = strings.TrimLeft(s, " \t\n\f\r")
224 if !strings.HasPrefix(s, "=") {
228 s = strings.TrimLeft(s, " \t\n\f\r")
232 if q := s[0]; q == '"' || q == '\'' {
234 closeQuote := strings.IndexRune(s, rune(q))
235 if closeQuote == -1 {
238 return s[:closeQuote]
241 end := strings.IndexAny(s, "; \t\n\f\r")
250 var boms = []struct {
254 {[]byte{0xfe, 0xff}, "utf-16be"},
255 {[]byte{0xff, 0xfe}, "utf-16le"},
256 {[]byte{0xef, 0xbb, 0xbf}, "utf-8"},