Documentation
¶
Overview ¶
Package htmlutil implements utility functions and wrappers for working with HTML content, including some DOM-like helpers for getting node text, sniffing character encoding, parsing attributes, and handling URLs.
The helpers work on the tokens of an htmlstream.Reader or htmlstream.Transformer as they are read, without building a tree.
Element categories classify HTML elements (in the XHTML namespace) by their start or end tags, open elements, or names (see NamedElement): IsVoid, IsHeadContent, IsBlock, IsTextBreak, IsHidden, IsHeading, IsPreformatted, IsFormatting and IsSpecial.
Stack keeps a value for open elements, pushed at their start tags and popped at their end tags, explicit or implied. Document tracks where the html, head and body elements start and end, including the ones HTML parsers imply, and whether the document is in quirks mode.
InnerText reads the text of an element approximating the DOM's innerText, and TextContent like its textContent, and TextBuilder and CollapseSpace collapse whitespace like rendered text. ScriptType, IsJavaScriptType and IsJSONType classify script elements, and CutCDATAWrapper removes the CDATA section wrapper of script and style contents. MetaCharset returns the character encoding a meta element declares, and PrescanCharset finds the one declared at the start of a document, before reading it.
URLAttrs returns the attributes of a start tag which contain URLs, and ParseSrcset the URLs of a srcset attribute. BaseURL tracks the base URL set by a base element, CleanURL removes the characters browsers ignore in URLs, and ResolveURL resolves URLs with net/url.
The helpers based on a specification cite it, and say where they differ from it.
Example ¶
Make the URLs of a document absolute, as when saving or embedding a page. BaseURL tracks the base element, URLAttrs finds the attributes with URLs, and a srcset attribute has a list of them. URLs which can't be resolved are left as they are.
package main
import (
"net/url"
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<base href="/docs/"><a href=intro.html>Intro</a> <a href="http://[bad">Bad</a> <img src=a.png srcset="a-2x.png 2x, http://[bad 3x" alt="A">`
doc, err := url.Parse("https://example.com/en/index.html")
if err != nil {
panic(err)
}
base := htmlutil.NewBaseURL(doc)
x := htmlstream.NewTransformer(os.Stdout, strings.NewReader(page))
for x.Next() {
tok := x.Token()
base.Update(tok)
for name, a := range htmlutil.URLAttrs(tok) {
var value string
if htmlutil.IsSrcset(a) {
var cs []string
for c := range htmlutil.ParseSrcset(a.Value()) {
if u, err := base.Resolve(c.URL); err == nil {
c.URL = u.String()
}
cs = append(cs, strings.TrimSpace(c.URL+" "+c.Descriptor))
}
value = strings.Join(cs, ", ")
} else if u, err := base.Resolve(a.Value()); err == nil {
value = u.String()
} else {
continue
}
if err := x.SetAttr(name, value); err != nil {
panic(err)
}
}
}
if err := x.Close(); err != nil {
panic(err)
}
}
Output: <base href="https://example.com/docs/"><a href="https://example.com/docs/intro.html">Intro</a> <a href="http://[bad">Bad</a> <img src="https://example.com/docs/a.png" srcset="https://example.com/docs/a-2x.png 2x, http://[bad 3x" alt="A">
Index ¶
- func CleanURL(s string) string
- func CollapseSpace(s string) string
- func CutCDATAWrapper[T ~string | ~[]byte](s T, w CDATAWrapper) (inner T, found bool)
- func InnerText(r *htmlstream.Reader, opt TextOptions) (s string, truncated bool)
- func IsBlock[E NamedElement](e E) bool
- func IsFormatting[E NamedElement](e E) bool
- func IsHeadContent[E NamedElement](e E) bool
- func IsHeading[E NamedElement](e E) bool
- func IsHidden[E NamedElement](e E) bool
- func IsJSONType(t string) bool
- func IsJavaScriptType(t string) bool
- func IsPreformatted[E NamedElement](e E) bool
- func IsSpecial[E NamedElement](e E) bool
- func IsSrcset(a htmlstream.Attr) bool
- func IsTextBreak[E NamedElement](e E) bool
- func IsVoid[E NamedElement](e E) bool
- func MetaCharset(tok *htmlstream.Token) (name string, ok bool)
- func ParseSrcset(v string) iter.Seq[SrcsetCandidate]
- func PrescanCharset(head []byte) (name string, ok bool)
- func ResolveURL(base *url.URL, ref string) (*url.URL, error)
- func ScriptType(tok *htmlstream.Token) string
- func TextContent(r *htmlstream.Reader, limit int) (s string, truncated bool)
- func URLAttrs(tok *htmlstream.Token) iter.Seq2[string, htmlstream.Attr]
- type BaseURL
- type CDATAWrapper
- type Document
- type DocumentEvent
- type DocumentPart
- type HTMLName
- type NamedElement
- type SrcsetCandidate
- type Stack
- func (s *Stack[T]) All() iter.Seq2[int, *T]
- func (s *Stack[T]) At(i int) *T
- func (s *Stack[T]) Closes(tok *htmlstream.Token) bool
- func (s *Stack[T]) Len() int
- func (s *Stack[T]) Pop(tok *htmlstream.Token) (T, bool)
- func (s *Stack[T]) Push(tok *htmlstream.Token, v T) bool
- func (s *Stack[T]) Top() (*T, bool)
- type TextBuilder
- func (t *TextBuilder) Break()
- func (t *TextBuilder) Bytes() []byte
- func (t *TextBuilder) Len() int
- func (t *TextBuilder) Reset()
- func (t *TextBuilder) String() string
- func (t *TextBuilder) Write(p []byte) (int, error)
- func (t *TextBuilder) WriteString(s string) (int, error)
- func (t *TextBuilder) WriteText(tok *htmlstream.Token)
- type TextOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CleanURL ¶
CleanURL removes leading and trailing C0 control characters and spaces, and all ASCII tabs and newlines, following the first steps of the URL Standard parser.
func CollapseSpace ¶
CollapseSpace returns s with runs of ASCII whitespace collapsed into single spaces, and leading and trailing whitespace removed, like the Infra Standard's strip and collapse ASCII whitespace (see TextBuilder).
func CutCDATAWrapper ¶
func CutCDATAWrapper[T ~string | ~[]byte](s T, w CDATAWrapper) (inner T, found bool)
CutCDATAWrapper removes a CDATA section wrapped in comments around the contents s of a script or style element, which XHTML and polyglot markup use so that XML parsers read the contents without escaping and HTML parsers ignore the markers (e.g., //<![CDATA[ and //]]> in a script). The forms removed are given by w: CDATALineComment|CDATABlockComment for JavaScript, and CDATABlockComment for CSS, each with CDATAHTMLComment to also remove the forms with HTML comment markers (not for JavaScript modules), and with CDATABare to also remove a CDATA section without comments from contents read as XML. The start and the end may be in different forms.
Only a single wrapper around all of s is removed: s must start with the start marker and end with the end marker, with only whitespace before and after them, and the contents between them must not contain "]]>", which ends a CDATA section, other than in "]]]]><![CDATA[>" (the usual way to write "]]>" in a CDATA section, which XML parsers read as "]]>", and which is left as it is). Otherwise (e.g., with code before the start marker or after the end marker, several wrapped parts, or nested wrappers), nothing is removed.
Spaces and tabs are allowed inside the comments of the CDATALineComment and CDATABlockComment forms; the markers of the CDATAHTMLComment and CDATABare forms must be as written above. The whitespace before the start and after the end is removed, and so are the spaces and tabs next to the start and the end on their lines, and one line end after the start and before the end. A line comment start is only removed at the end of its line, so that the code after it stays commented out, and so is a CDATAHTMLComment start. A CDATAHTMLComment end is only removed at the start of its line, where JavaScript allows -->.
The <!-- of the CDATAHTMLComment forms puts script contents in the escaped state of the HTML tokenizer, where "<script" starts a nested script whose end tag doesn't end the element, so these forms aren't removed from contents containing "<script" (in any case).
If s doesn't start and end with a wrapper, CutCDATAWrapper returns s and false.
func InnerText ¶
func InnerText(r *htmlstream.Reader, opt TextOptions) (s string, truncated bool)
InnerText reads the contents of the element opened by the current start tag, returning its text, and whether it was truncated to TextOptions.Max bytes. Afterwards, the current token is the element's end tag. If the current token doesn't open an element, it returns an empty string. Read errors are returned by the Reader's Err method.
Unless TextOptions.KeepWhitespace is set, the text approximates the DOM's innerText (the rendered text collection steps) with the default styles of HTML elements:
- The contents of elements which aren't rendered are left out: those of IsHidden (canvas and noscript only if the Reader has scripting enabled, which isn't the default, see htmlstream.Reader.SetScripting), HTML elements other than embed with a hidden attribute, dialog elements without an open attribute, and other elements with a popover attribute, which the rendering section hides, and the contents of details elements without an open attribute other than their first summary child.
- The contents of SVG clipPath, defs, desc, filter, linearGradient, marker, mask, metadata, pattern, radialGradient, script, style, symbol and title elements, which aren't rendered, are left out, and so are the children of MathML semantics and maction elements after their first child element (e.g., annotation and annotation-xml elements after the presentation markup). SVG and MathML elements are those in their namespaces (see htmlstream.Token.NS).
- The contents of elements with hidden="until-found" are left out where browsers hide them with content-visibility: hidden, which applies to block-level elements, table cells, and button, select and object elements, but not to other inline elements or to table rows and row groups.
- Whitespace is collapsed except in preformatted elements (see IsPreformatted), and removed at the start and end of lines.
- Block-level elements (see IsBlock) other than table rows and row groups are on lines of their own, and p elements are separated from the text around them by a blank line.
- br is a line break, the cells of a table row are separated by tabs, and the rows of a table by line breaks.
It differs from innerText where the result depends on the styles of the document (e.g., display and visibility) or on layout, and in details of the white space processing of CSS (e.g., CSS doesn't collapse form feeds). The fallback content of object elements is included, and so is content which HTML parsers move elsewhere (e.g., text in a table outside the cells, which they move before the table). Where browsers differ, it follows Chromium for drop-down select elements (Firefox leaves out their options) and table cells with hidden="until-found" (Firefox doesn't hide them), and Firefox for svg and math elements (Chromium puts them on lines of their own, and renders mi elements in mathematical italic), the contents of clipPath, defs, marker, mask, pattern and symbol elements (Chromium includes their text, but not the contents of foreignObject elements in them), switch elements, whose children are all included (Chromium only renders the first), and semantics and maction elements, whose text and first child element are included (Chromium leaves out the text in them, and the annotation elements in semantics elements). If the element itself isn't rendered (see above), the text is its text content, as innerText returns for elements which aren't rendered; whether the enclosing elements are rendered isn't known.
Template contents are never included, since HTML parsers put them in a separate document fragment, and a newline directly after the start tag of a pre, listing or textarea element is left out, like HTML parsers do (it is kept under XML rules, like XML parsers do; see htmlstream.Token.HTMLRules).
Under HTML rules, NUL in text and CDATA sections is left out in HTML content, including integration points like foreignObject, and replaced with U+FFFD in SVG and MathML content, as in browsers (the tokenizer replaces it in title, textarea, script and style contents, see htmlstream.Token.AppendText). Like browsers, InnerText also leaves out a newline after NUL directly after the start tag of a pre or listing element. Under XML rules, NUL is kept.
With XML syntax (see htmlstream.Reader.SetXMLSyntax, which applies to the documents read like in HTML mode in htmlstream.Universal mode), the contents of title, textarea, script and style elements are text up to their end tag, as in HTML parsers, so a CDATA section in them is text, markers included, with character references decoded in title and textarea. XML parsers read it as a CDATA section, without the markers, and the polyglot package removes a CDATA section around all of the contents. CutCDATAWrapper with CDATABare removes such a section from the text.
TextContent returns the text like the DOM's textContent instead, and CollapseSpace puts the result on one line.
Example ¶
InnerText approximates the text a browser renders. TextContent returns all the text in the element, like the DOM's textContent.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<article>
<h1>Fish & chips</h1>
<p>Serves two.<br>Takes <b>20</b> minutes.</p>
<table><tr><th>Item<th>Price<tr><td>Fish<td>4</table>
<script>track()</script><p hidden>Hidden</p>
</article>`
r := htmlstream.NewReader(strings.NewReader(page))
r.Find(htmlstream.Tag("article"))
text, _ := htmlutil.InnerText(r, htmlutil.TextOptions{})
if err := r.Err(); err != nil {
panic(err)
}
fmt.Printf("%s\n---\n", text)
r = htmlstream.NewReader(strings.NewReader(page))
r.Find(htmlstream.Tag("article"))
text, _ = htmlutil.TextContent(r, 0)
if err := r.Err(); err != nil {
panic(err)
}
fmt.Printf("%q\n", htmlutil.CollapseSpace(text))
}
Output: Fish & chips Serves two. Takes 20 minutes. Item Price Fish 4 --- "Fish & chips Serves two.Takes 20 minutes. ItemPriceFish4 track()Hidden"
func IsBlock ¶
func IsBlock[E NamedElement](e E) bool
IsBlock reports whether e is a block-level HTML element: text before and after it is on separate lines when rendered. These are the elements the rendering section of the HTML Standard gives a block-level display (block, list-item, table or table-caption; e.g., p, li, table and caption), and table rows and row groups (tr, tbody, thead and tfoot), whose rows are on separate lines. Table cells and inline-block elements (e.g., button and select) aren't block-level. Styles set by the document aren't taken into account.
Example ¶
The element categories classify start and end tags of HTML elements. The title in svg is an SVG element.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<p><b><br><td><h2><pre><img><svg><title></title></svg><title></title><script></script>`
r := htmlstream.NewReader(strings.NewReader(page))
for r.Next() {
tok := r.Token()
if tok.Kind() != htmlstream.StartTag {
continue
}
var cats []string
for _, c := range []struct {
name string
fn func(*htmlstream.Token) bool
}{
{"block", htmlutil.IsBlock[*htmlstream.Token]},
{"text-break", htmlutil.IsTextBreak[*htmlstream.Token]},
{"void", htmlutil.IsVoid[*htmlstream.Token]},
{"heading", htmlutil.IsHeading[*htmlstream.Token]},
{"preformatted", htmlutil.IsPreformatted[*htmlstream.Token]},
{"hidden", htmlutil.IsHidden[*htmlstream.Token]},
{"head-content", htmlutil.IsHeadContent[*htmlstream.Token]},
{"formatting", htmlutil.IsFormatting[*htmlstream.Token]},
{"special", htmlutil.IsSpecial[*htmlstream.Token]},
} {
if c.fn(tok) {
cats = append(cats, c.name)
}
}
if len(cats) == 0 {
cats = append(cats, "-")
}
fmt.Printf("%-8s %s\n", tok.Raw(), strings.Join(cats, " "))
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: <p> block text-break special <b> formatting <br> text-break void special <td> text-break special <h2> block text-break heading special <pre> block text-break preformatted special <img> void special <svg> - <title> - <title> hidden head-content special <script> hidden head-content special
func IsFormatting ¶
func IsFormatting[E NamedElement](e E) bool
IsFormatting reports whether e is an HTML element in the formatting category of the HTML Standard's parsing rules (a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt and u), which HTML parsers keep in the list of active formatting elements and reopen after misnested end tags.
func IsHeadContent ¶
func IsHeadContent[E NamedElement](e E) bool
IsHeadContent reports whether e is an HTML element allowed in the head: those the in head insertion mode of HTML parsers handles (base, basefont, bgsound, link, meta, noframes, noscript, script, style, template and title). Other elements, and text other than whitespace, end the head. HTML parsers also put these elements in the head when they come after it, except noscript.
func IsHeading ¶
func IsHeading[E NamedElement](e E) bool
IsHeading reports whether e is an HTML heading element, one of the h1 to h6 elements. Heading content in the HTML Standard also includes hgroup, which IsHeading doesn't.
func IsHidden ¶
func IsHidden[E NamedElement](e E) bool
IsHidden reports whether e is an HTML element whose contents aren't rendered as text. These are the elements with contents which the rendering section of the HTML Standard hides (datalist, head, noembed, noframes, rp, script, style, template and title, and noscript when scripting is enabled), and those with contents which browsers render as replaced elements or widgets instead: audio, canvas (when scripting is enabled; otherwise it renders its fallback content), iframe, meter, progress, textarea (whose contents are the initial value of the form control) and video. It includes noscript and canvas whether scripting is enabled or not: callers check htmlstream.Reader.Scripting, as InnerText does. The void elements it hides (e.g., area and meta) have no contents and aren't included. Elements hidden by their attributes (e.g., hidden) aren't included either, since end tags have no attributes (see InnerText, which leaves them out). The fallback content of object elements, which browsers render when they can't load the object, is not hidden.
To skip the contents, call htmlstream.Reader.Skip at the start tag.
func IsJSONType ¶
IsJSONType reports whether a script type (see ScriptType) is JSON: the importmap and speculationrules types (compared ASCII case-insensitively), or a JSON MIME type as defined by the MIME Sniffing Standard: one whose essence (the MIME type without parameters, lowercased) is application/json or text/json, or whose subtype ends with +json (e.g., application/ld+json).
func IsJavaScriptType ¶
IsJavaScriptType reports whether a script type (see ScriptType) is JavaScript, compared ASCII case-insensitively: module, or one of the JavaScript MIME types listed in the MIME Sniffing Standard.
func IsPreformatted ¶
func IsPreformatted[E NamedElement](e E) bool
IsPreformatted reports whether e is an HTML element whose contents keep their whitespace when rendered: those the rendering section of the HTML Standard gives white-space: pre (pre, listing, xmp and plaintext) or pre-wrap (textarea). HTML parsers also drop a newline directly after the start tag of pre, listing and textarea.
func IsSpecial ¶
func IsSpecial[E NamedElement](e E) bool
IsSpecial reports whether e is an HTML element in the special category of the HTML Standard's parsing rules (block-level elements, table parts, head content, form controls, etc.), whose end tag rules differ from those of other elements: an end tag of another element inside an open special element is ignored. The SVG and MathML elements in the category (e.g., foreignObject and mi) aren't included.
func IsSrcset ¶
func IsSrcset(a htmlstream.Attr) bool
IsSrcset reports whether an attribute contains a srcset list of URLs (see ParseSrcset).
func IsTextBreak ¶
func IsTextBreak[E NamedElement](e E) bool
IsTextBreak reports whether e separates words in the text of an element: a block-level element (see IsBlock), a table cell (td or th), or br.
func IsVoid ¶
func IsVoid[E NamedElement](e E) bool
IsVoid reports whether e is an HTML void element, which has no end tag and which HTML parsers never open: those which serialize as void in the HTML Standard (the void elements, e.g., br and img, and basefont, bgsound, frame, keygen and param), and image under HTML rules, which HTML parsers turn into img.
It classifies e by its name and namespace only: whether a start tag opens an element is htmlstream.Token.Opens. Under XML rules and with XML syntax, a void element can open one: a br start tag in htmlstream.HTML mode with htmlstream.Reader.SetXMLSyntax, or in the XHTML namespace in a document read like in XML mode in htmlstream.Universal mode, is void, but unless it is self-closed, it opens an element, closed by its end tag or an implied one.
func MetaCharset ¶
func MetaCharset(tok *htmlstream.Token) (name string, ok bool)
MetaCharset returns the name of the character encoding declared by a meta element, as HTML parsers read the start tag in the in head insertion mode: the encoding of the charset attribute if its value is an encoding label (see the Encoding Standard), or else, if the http-equiv attribute is an ASCII case-insensitive match for Content-Type, the encoding the algorithm for extracting a character encoding from a meta element gets from the content attribute. It returns false for other tokens, and for meta elements without a declaration it recognizes.
The name is the one the Encoding Standard gives the encoding (e.g., "UTF-8", or "windows-1252" for the label "latin1"), which golang.org/x/text/encoding/htmlindex.Get accepts. Like the steps to change the encoding, which HTML parsers run with the declaration, it gives UTF-8 for UTF-16BE and UTF-16LE, and windows-1252 for x-user-defined. Some labels (e.g., "iso-2022-kr") give the replacement encoding, which decodes any non-empty input to a single U+FFFD.
HTML parsers use the first declaration they read, unless the encoding was already certain (e.g., from a byte order mark or the Content-Type header). Before parsing, browsers look for it with the prescan (see PrescanCharset).
Example ¶
MetaCharset returns the encoding a meta element declares, with the encoding names of the Encoding Standard.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<meta charset=UTF-8>
<meta charset=latin1>
<meta http-equiv=Content-Type content="text/html; charset=utf-16">
<meta http-equiv=content-type content="text/html">
<meta charset=unknown>
<meta name=viewport content="width=device-width">`
r := htmlstream.NewReader(strings.NewReader(page))
for r.Find(htmlstream.Tag("meta")) {
name, ok := htmlutil.MetaCharset(r.Token())
fmt.Printf("%q %t\n", name, ok)
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: "UTF-8" true "windows-1252" true "UTF-8" true "" false "" false "" false
func ParseSrcset ¶
func ParseSrcset(v string) iter.Seq[SrcsetCandidate]
ParseSrcset returns an iterator over the image candidates in a srcset attribute value, following the HTML Standard algorithm to parse a srcset attribute. Like in browsers, candidates with invalid descriptors are left out. A candidate can have no descriptors, an x descriptor, a w descriptor, or a w and an h descriptor in either order. The value of a w or h descriptor is a non-zero valid non-negative integer (ASCII digits, e.g., "100w" or "080h"), and that of an x descriptor is a non-negative valid floating-point number (e.g., "2x", ".5x", "1.5e1x" or "-0x", but not "1.x", "+1x" or "-1x"). Any other descriptor is invalid, including descriptors in another case ("2X") and with parentheses ("(max-width: 1px)"). An x value too large for a float64 is invalid, as the rules for parsing floating-point number values return an error for it.
It differs from the HTML Standard in that w and h values too large for an int are clamped to math.MaxInt. It only parses the attribute: selecting an image, which adds the img src attribute as a 1x candidate, computes the density of w candidates from the sizes attribute, and ignores candidates with the same density as an earlier one, isn't done.
Example ¶
ParseSrcset splits a srcset attribute into image candidates, leaving out those with invalid descriptors. A URL ends at whitespace, so it can contain commas.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
for c := range htmlutil.ParseSrcset("small.jpg 480w, large.jpg 1200w 900h,huge.jpg 2X, data:image/png;base64,AA== 1.5x, a.jpg") {
fmt.Printf("%q %q w=%d x=%g h=%d\n", c.URL, c.Descriptor, c.Width, c.Density, c.Height)
}
}
Output: "small.jpg" "480w" w=480 x=0 h=0 "large.jpg" "1200w 900h" w=1200 x=0 h=900 "data:image/png;base64,AA==" "1.5x" w=0 x=1.5 h=0 "a.jpg" "" w=0 x=1 h=0
func PrescanCharset ¶
PrescanCharset returns the name of the character encoding declared at the start of an HTML document, following the HTML Standard's algorithm to prescan a byte stream to determine its encoding, which browsers run on the first bytes of a document before parsing it. head is the start of the document: its first 1024 bytes, or the whole document if it is shorter. The HTML Standard encourages prescanning that many bytes, and documents must declare their encoding within them. A declaration cut off by the end of head isn't found.
The prescan looks for the first meta element which declares an encoding, and gives the same encoding names and substitutions as MetaCharset. It reads bytes, not tokens: it skips comments, the attributes of other tags, and other markup up to the next ">", and finds meta elements anywhere else, including in the contents of raw text elements like script and title. Character references in attribute values aren't decoded, and a charset attribute with an unknown label prevents the content attribute from being used. It returns false if it doesn't find a declaration, except that:
- If head starts with "<?x" in UTF-16, which the prescan checks first, it returns UTF-16LE or UTF-16BE.
- If head starts with an XML declaration with an encoding (e.g., <?xml version="1.0" encoding="ISO-8859-2"?>), it returns that encoding, with UTF-16BE and UTF-16LE replaced with UTF-8. As in the algorithm, the declaration is only checked if no meta element declares an encoding, and x-user-defined isn't replaced.
It doesn't check for a byte order mark, which comes first in the HTML Standard's encoding sniffing algorithm, followed by the charset parameter of the Content-Type header, which also takes precedence over the prescan. For example, with golang.org/x/text/encoding/htmlindex, golang.org/x/text/encoding/unicode and golang.org/x/text/transform:
br := bufio.NewReader(r)
head, _ := br.Peek(1024) // the whole input if it is shorter
name, ok := htmlutil.PrescanCharset(head)
if !ok {
name = "windows-1252" // or another default
}
enc, err := htmlindex.Get(name)
if err != nil {
return err
}
// BOMOverride decodes UTF-8 or UTF-16 instead if there is a byte order
// mark, and removes it.
rd := htmlstream.NewReader(transform.NewReader(br, unicode.BOMOverride(enc.NewDecoder())))
Example ¶
PrescanCharset finds the encoding declared at the start of a document, before reading it. The prescan skips comments, but not the contents of script elements.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
for _, head := range []string{
`<!DOCTYPE html><html><head><meta charset="Shift_JIS"><title>x</title>`,
`<!-- <meta charset=utf-8> --><meta http-equiv=content-type content="text/html; charset=iso-8859-2">`,
`<meta content="text/html; charset=iso-8859-2">`,
`<script>document.write("<meta charset=koi8-r>")</script>`,
`<?xml version="1.0" encoding="windows-1251"?><html>`,
`<p>No declaration`,
} {
name, ok := htmlutil.PrescanCharset([]byte(head))
fmt.Printf("%q %t\n", name, ok)
}
}
Output: "Shift_JIS" true "ISO-8859-2" true "" false "KOI8-R" true "windows-1251" true "" false
func ResolveURL ¶
ResolveURL parses ref (after CleanURL) and resolves it against base, if not nil. Unlike url.URL.ResolveReference, the result only has a fragment if ref has one, like in browsers.
It parses URLs with url.Parse, not the URL Standard parser browsers use, so some URLs are parsed differently: e.g., backslashes in http and https URLs aren't read as slashes, hosts aren't normalized (IDNA, IPv4 address forms), and characters aren't percent-encoded the same way. Some URLs browsers accept are errors.
Example ¶
ResolveURL resolves a URL like browsers do for the cases net/url handles: tabs and newlines are removed, and the fragment of the base isn't kept.
package main
import (
"fmt"
"net/url"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
base, _ := url.Parse("https://example.com/a/b.html#section")
for _, ref := range []string{"c.html", " ../d\n.html ", "?q=1", "", "mailto:a@example.com"} {
u, err := htmlutil.ResolveURL(base, ref)
if err != nil {
panic(err)
}
fmt.Printf("%q: %s\n", ref, u)
}
}
Output: "c.html": https://example.com/a/c.html " ../d\n.html ": https://example.com/d.html "?q=1": https://example.com/a/b.html?q=1 "": https://example.com/a/b.html "mailto:a@example.com": mailto:a@example.com
func ScriptType ¶
func ScriptType(tok *htmlstream.Token) string
ScriptType returns the type of a script start tag, ASCII-lowercased, as the HTML Standard determines it (the script block's type string): "text/javascript" if the type attribute is empty, or if it is missing and the language attribute is empty or missing; otherwise the type attribute with leading and trailing ASCII whitespace removed (so " module " is "module", and a type attribute of only whitespace gives "", which is neither JavaScript nor JSON); otherwise "text/" followed by the language attribute.
Parameters are kept, so "text/javascript; charset=utf-8" isn't a JavaScript type, as in browsers, which don't run such scripts.
Example ¶
ScriptType determines the type of a script like browsers do, to tell classic scripts and modules apart from data blocks.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<script>a()</script>
<script type=module>b()</script>
<script type="text/JavaScript ">c()</script>
<script language=VBScript>d</script>
<script type=application/ld+json>{}</script>
<script type=importmap>{}</script>
<script type="text/javascript; charset=utf-8">e()</script>
<script type=text/template><p>{{x}}</p></script>`
r := htmlstream.NewReader(strings.NewReader(page))
for r.Find(htmlstream.Tag("script")) {
t := htmlutil.ScriptType(r.Token())
fmt.Printf("%-33q js=%-5t json=%t\n", t, htmlutil.IsJavaScriptType(t), htmlutil.IsJSONType(t))
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: "text/javascript" js=true json=false "module" js=true json=false "text/javascript" js=true json=false "text/vbscript" js=false json=false "application/ld+json" js=false json=true "importmap" js=false json=true "text/javascript; charset=utf-8" js=false json=false "text/template" js=false json=false
func TextContent ¶
func TextContent(r *htmlstream.Reader, limit int) (s string, truncated bool)
TextContent reads the contents of the element opened by the current start tag like InnerText, returning its text like the DOM's textContent: all the text in the element as it is (including CDATA sections, and with XML syntax, the markers of those in title, textarea, script and style elements, see InnerText, which also describes how NUL is left out or replaced), including the contents of hidden elements like script and style, but not template contents. It is InnerText with TextOptions{KeepWhitespace: true, Hidden: true, Max: limit}: if limit is positive, the text is truncated to limit bytes, and TextContent reports it. Read errors are returned by the Reader's Err method.
Example ¶
TextContent returns the text of an element as it is, except for template contents and the newline HTML parsers drop after the start tag of pre. Here it is truncated to 20 bytes.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<pre>
for i := range 3 {
print(i)
}</pre>
<p>A <b>long</b> <template>x</template>paragraph with spaces.</p>`
r := htmlstream.NewReader(strings.NewReader(page))
for r.Find(htmlstream.Or(htmlstream.Tag("pre"), htmlstream.Tag("p"))) {
text, truncated := htmlutil.TextContent(r, 20)
fmt.Printf("%q %t\n", text, truncated)
}
}
Output: "for i := range 3 {\n\t" true "A long paragraph wi" true
Example (ReadError) ¶
The text helpers have no error result: a read error stops the Reader, cutting off the text, and Err returns it. A function which returns its own error for text it can't parse can check Err in a deferred function, so that it returns the read error instead, which comes first.
package main
import (
"errors"
"fmt"
"io"
"strings"
"testing/iotest"
"time"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
// eventDates returns the dates of the time elements of an HTML document.
func eventDates(r io.Reader) (dates []time.Time, err error) {
rd := htmlstream.NewReader(r)
rd.SetMaxTokenSize(64 << 10)
defer func() {
if rerr := rd.Err(); rerr != nil {
err = rerr // it stopped the Reader, and may have cut off the text which failed to parse
}
}()
for rd.Find(htmlstream.Tag("time")) {
s, _ := htmlutil.TextContent(rd, 64)
d, err := time.Parse(time.DateOnly, strings.TrimSpace(s))
if err != nil {
return nil, fmt.Errorf("event date: %w", err)
}
dates = append(dates, d)
}
return dates, nil // the deferred function reports a read error
}
// The text helpers have no error result: a read error stops the Reader,
// cutting off the text, and Err returns it. A function which returns its own
// error for text it can't parse can check Err in a deferred function, so that
// it returns the read error instead, which comes first.
func main() {
const page = `<ul><li><time>2026-10-30</time> Launch<li><time>2026-11-05</time> Review</ul>`
for _, r := range []io.Reader{
strings.NewReader(page),
strings.NewReader(strings.Replace(page, "11-05", "11-5", 1)),
io.MultiReader(strings.NewReader(page[:54]), iotest.ErrReader(errors.New("connection reset"))),
} {
dates, err := eventDates(r)
if err != nil {
fmt.Println("error:", err)
continue
}
var s []string
for _, d := range dates {
s = append(s, d.Format("Mon Jan 2"))
}
fmt.Println(strings.Join(s, ", "))
}
}
Output: Fri Oct 30, Thu Nov 5 error: event date: parsing time "2026-11-5" as "2006-01-02": cannot parse "5" as "02" error: connection reset
func URLAttrs ¶
func URLAttrs(tok *htmlstream.Token) iter.Seq2[string, htmlstream.Attr]
URLAttrs returns an iterator over the lowercase names and the attributes of a start tag whose values are URLs (e.g., a href, img src), or srcset lists of URLs (see IsSrcset).
For HTML elements, these are the attributes the HTML Standard defines as URLs or srcset lists: a, area, base and link href; img, script, iframe, embed, audio, video, source, track and input src; img and source srcset and link imagesrcset; video poster; object data; form action; button and input formaction; and blockquote, q, del and ins cite. The ping attribute (a list of URLs) and the microdata itemid, itemprop and itemtype attributes (identifiers) aren't included. Of the obsolete attributes, it includes frame src; img, iframe and frame longdesc; and background, which browsers load on the elements the rendering section lists (body, table, thead, tbody, tfoot, tr, td and th), but not others like lowsrc, html manifest and object codebase. An image element in the XHTML namespace has the URL attributes of img under HTML rules (see htmlstream.Token.HTMLRules), as HTML parsers turn it into img.
For the SVG elements a, feImage, image, script and use, the URL attribute is href, or if there is no href, xlink:href. SVG 2 specifies that xlink:href is ignored if href is present, as browsers do. Under HTML rules, xlink:href is the attribute with that name, which HTML parsers put in the XLink namespace; an attribute with another prefix is in no namespace for them, whatever it is bound to. Otherwise, it is the href attribute in the XLink namespace (see htmlstream.Token.AttrNamespace), whose name is given as "xlink:href" whatever its prefix.
Other elements, and URL attributes which usually refer to the same document (like the href of SVG gradients and animation elements), are not included.
Types ¶
type BaseURL ¶
type BaseURL struct {
// contains filtered or unexported fields
}
BaseURL tracks the base URL of an HTML document like the HTML Standard defines it (the frozen base URL): the href of the first base element with one, resolved against the document URL. Base elements in template contents, which HTML parsers put in a separate document fragment, are left out.
In a single pass, links before the base element can't be resolved against it. A base element is usually in the head, so links can be held until the head ends (see Document).
The zero value is like the BaseURL NewBaseURL returns for a nil document URL.
Example ¶
BaseURL tracks the base element, which applies to the URLs after it.
package main
import (
"fmt"
"net/url"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<head><base href="/docs/"><link rel=stylesheet href=style.css></head>
<body background=bg.png><a href="../about#team">About</a>
<svg><a href="b.svg"><image xlink:href=c.png /></a></svg>`
doc, err := url.Parse("https://example.com/en/index.html")
if err != nil {
panic(err)
}
base := htmlutil.NewBaseURL(doc)
r := htmlstream.NewReader(strings.NewReader(page))
for r.Next() {
tok := r.Token()
base.Update(tok)
for name, a := range htmlutil.URLAttrs(tok) {
u, err := base.Resolve(a.Value())
if err != nil {
continue
}
fmt.Printf("%s %s: %s\n", tok.Name(), name, u)
}
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: base href: https://example.com/docs/ link href: https://example.com/docs/style.css body background: https://example.com/docs/bg.png a href: https://example.com/about#team a href: https://example.com/docs/b.svg image xlink:href: https://example.com/docs/c.png
func NewBaseURL ¶
NewBaseURL returns a BaseURL for a document at the URL doc (which may be nil).
func (*BaseURL) Resolve ¶
Resolve resolves ref against the current base URL (see ResolveURL), which is nil if the document URL is nil and no base element set one.
func (*BaseURL) Seen ¶
Seen reports whether a base element with an href was seen. Later base elements don't change the base URL.
func (*BaseURL) URL ¶
URL returns the current base URL, or nil if the document URL is nil and no base element set one.
func (*BaseURL) Update ¶
func (b *BaseURL) Update(tok *htmlstream.Token) bool
Update processes the next token, returning true if it set the base URL. It must be called with every start and end tag, to track template elements. A base href which can't be parsed (see ResolveURL), or is a data: or javascript: URL, leaves the document URL as the base URL, like in browsers.
type CDATAWrapper ¶
type CDATAWrapper uint8
CDATAWrapper is a set of forms of the CDATA section wrapper removed by CutCDATAWrapper.
const ( // CDATALineComment is the form with JavaScript line comments: // //<![CDATA[ at the end of a line, and //]]>. CDATALineComment CDATAWrapper = 1 << iota // CDATABlockComment is the form with JavaScript and CSS block comments: // /*<![CDATA[*/ and /*]]>*/. CDATABlockComment // CDATAHTMLComment adds the forms which also have HTML comment markers, // written by CMSs such as Drupal 7. With CDATALineComment, it adds the // form for JavaScript, <!--//--><![CDATA[//><!-- and //--><!]]>, where // the line starting with <!-- is a comment (an HTML-like comment, which // JavaScript modules don't allow). With CDATABlockComment, it adds the // form for CSS, <!--/*--><![CDATA[/*><!--*/ and /*]]>*/-->, whose // markers are also JavaScript comments (except in modules). CSS ignores // <!-- and --> at the top level of a style sheet; after contents leaving // a block open or a rule unfinished (e.g., @import "a.css" without a // semicolon), --> is part of the last declaration or rule instead, which // isn't checked. CDATAHTMLComment // CDATABare is the form without comments, <![CDATA[ and ]]>, which // XHTML documents use. Only XML parsers read it as a CDATA section: // HTML parsers read the markers as part of the script or style, where // they are syntax errors, so it is only for contents read as XML (e.g., // with [htmlstream.Reader.SetXMLSyntax]), where removing it gives the // contents XML parsers read, without the whitespace around them. CDATABare )
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document tracks which part of an HTML document the tokens are in, like the first insertion modes of HTML parsers (initial, before html, before head, in head and after head, as the HTML Standard defines them): where the html, head and body elements start and end, including the ones HTML parsers imply. It follows them for documents with a body: it doesn't handle frameset documents, and a frameset start tag after the head starts the body. With scripting disabled (the Reader's default), it follows the Reader for noscript in a head without a start tag, which differs from HTML parsers (see htmlstream.Reader.SetScripting), and with XML syntax for a self-closed head start tag, which ends the head (see htmlstream.Reader.SetXMLSyntax). Template contents don't change the part, and html, head and body start tags in them are reported as MisplacedTag. Like HTML parsers, it ignores a start tag cut off by the end of the input (see htmlstream.Token.Incomplete).
Documents read under XML rules (see htmlstream.Token.HTMLRules: in htmlstream.XML mode, and documents read like in XML mode in htmlstream.Universal mode) have no implied elements, as XML parsers don't imply any. For them, Part follows the html, head and body elements in the input: the first html element at the top level, and the first head and body elements at the top level or in it, with the head before the body. Their names are compared exactly, and they must be in the XHTML namespace (see htmlstream.Token.NS), so an html element without a namespace declaration is an ordinary element. Other elements, including other html, head and body elements, don't change the part. Update reports only HeadEnd, at the end of the head element, and End reports nothing. Once a start or end tag is read, Quirks reports false for them, as XML parsers never use quirks mode.
The zero value is ready to use, at the start of a document.
Example ¶
Document reports where the html, head and body elements start and end, including those HTML parsers imply, before each token.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
for _, page := range []string{
"<!DOCTYPE html>\n<title>Title</title><meta charset=utf-8>\n<p>Text",
"<html><head><title>No doctype</title>",
} {
r := htmlstream.NewReader(strings.NewReader(page))
var doc htmlutil.Document
for r.Next() {
tok := r.Token()
if ev := doc.Update(tok); ev != 0 {
raw := string(tok.Raw())
if tok.Implied() {
raw = "implied </" + string(tok.Name()) + ">"
}
fmt.Printf("%s: %v, now %v\n", raw, ev, doc.Part())
}
}
if err := r.Err(); err != nil {
panic(err)
}
if ev := doc.End(); ev != 0 {
fmt.Printf("at the end: %v\n", ev)
}
fmt.Println("quirks:", doc.Quirks())
}
}
Output: <title>: ImpliedHTML|ImpliedHead, now InHead <p>: HeadEnd|ImpliedBody, now InBody quirks: false implied </head>: HeadEnd, now AfterHead implied </html>: ImpliedBody, now InBody quirks: true
func (*Document) End ¶
func (d *Document) End() DocumentEvent
End returns the structure changes at the end of the input: HTML parsers always create html, head and body elements.
func (*Document) Part ¶
func (d *Document) Part() DocumentPart
Part returns the part of the document the last token passed to Update is in.
func (*Document) Quirks ¶
Quirks reports whether HTML parsers parse the document in quirks mode, based on the tokens passed to Update so far: the first content isn't a doctype, or the doctype sets quirks mode in the initial insertion mode (e.g., it is a legacy one, or cut off by the end of the input). Limited-quirks mode (e.g., XHTML 1.0 Transitional) is reported as no-quirks mode, since it doesn't change parsing. HTML parsers don't use quirks mode for iframe srcdoc documents, which Document can't tell apart, and XML parsers never use it (see Document).
func (*Document) Started ¶
Started reports whether the tokens passed to Update so far ended the initial insertion mode of HTML parsers: a doctype, or content other than whitespace, comments and processing instructions. A doctype after that is ignored by HTML parsers.
func (*Document) Update ¶
func (d *Document) Update(tok *htmlstream.Token) DocumentEvent
Update processes the next token, returning the structure changes before it (and the head end, if tok is the end of the head). It must be called with every token, in order.
type DocumentEvent ¶
type DocumentEvent uint8
DocumentEvent is a set of changes to the document structure before a token, as bits.
const ( ImpliedHTML DocumentEvent = 1 << iota // the html element starts without a start tag ImpliedHead // the head element starts without a start tag HeadEnd // the head element ends (explicitly, implied, or without a start tag) ImpliedBody // the body element starts without a start tag MisplacedTag // an html, head or body start tag after the element started, which HTML parsers ignore, adding only the attributes of html and body start tags to the element )
func (DocumentEvent) String ¶
func (e DocumentEvent) String() string
String returns the names of the constants for the bits set in e, separated by "|", e.g., "ImpliedHTML|ImpliedHead", or "0" if none are set.
type DocumentPart ¶
type DocumentPart uint8
DocumentPart is the part of an HTML document a token is in. The parts are named after the insertion modes of HTML parsers.
const ( BeforeHTML DocumentPart = iota // before the html element BeforeHead // in the html element, before the head InHead // in the head element AfterHead // after the end of the head, before the body InBody // in the body )
func (DocumentPart) String ¶
func (p DocumentPart) String() string
String returns the name of the constant for p, e.g., "InHead".
type HTMLName ¶
type HTMLName string
HTMLName is the name of an HTML element, for classifying elements by name (e.g., IsBlock(HTMLName("div"))). Like HTML parsers, it ASCII-lowercases the name and replaces NUL with U+FFFD.
Example ¶
The categories also classify open elements and element names.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
fmt.Println(htmlutil.IsBlock(htmlutil.HTMLName("DIV")), htmlutil.IsBlock(htmlutil.HTMLName("span")))
r := htmlstream.NewReader(strings.NewReader(`<pre><b>x`))
for r.Next() {
if r.Token().Kind() == htmlstream.Text {
for e := range r.Stack() {
fmt.Printf("%s preformatted: %v\n", e.Name(), htmlutil.IsPreformatted(e))
}
}
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: true false b preformatted: false pre preformatted: true
func (HTMLName) AppendLocalName ¶
AppendLocalName appends the name, ASCII-lowercased and with NUL replaced with U+FFFD, to dst.
type NamedElement ¶
type NamedElement interface {
NS() string // the namespace URI
AppendLocalName(dst []byte) []byte // the local name, as HTML parsers give it for HTML elements
}
NamedElement is an element with a name, which the Is* functions classify: a start or end tag (*htmlstream.Token), an open element (htmlstream.Element), or an HTML element name (HTMLName). Other tokens have no namespace, and aren't in any category. The Is* functions don't allocate for these types.
type SrcsetCandidate ¶
type SrcsetCandidate struct {
// URL is the URL as it is in the attribute value, without trailing
// commas. It isn't resolved (see [ResolveURL]).
URL string
// Descriptor is the descriptors as written, separated by single spaces
// (e.g., "2x", "100w" or "100w 50h"), or empty if there are none.
Descriptor string
// Width is the value of the w descriptor, or 0 if there is none.
Width int
// Density is the value of the x descriptor. If there is neither a w nor
// an x descriptor, it is 1, the density the [HTML Standard] gives the
// candidate when [normalizing the source densities]. If there is a w
// descriptor, it is 0. It is never negative, but may be 0 with no w
// descriptor ("0x").
//
// [HTML Standard]: https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
// [normalizing the source densities]: https://html.spec.whatwg.org/multipage/images.html#normalise-the-source-densities
Density float64
// Height is the value of the h descriptor (future-compat-h in the
// [HTML Standard]), or 0 if there is none. It is only valid with a w
// descriptor, and isn't used to select an image.
//
// [HTML Standard]: https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
Height int
}
SrcsetCandidate is an image candidate in a srcset attribute.
type Stack ¶
type Stack[T any] struct { // contains filtered or unexported fields }
Stack keeps a value for some of the open elements, in sync with a Reader. Values are pushed on the start tag of an element, and popped on the element's end tag (explicit or implied), which is matched using htmlstream.Token.StartPos, so stray end tags and the end tags of other elements are ignored. The zero value is an empty Stack ready to use.
Pop only pops the innermost value, so every end tag must be passed to it: a value whose end tag isn't passed stays at the top, and the values below it aren't popped either. After htmlstream.Reader.Skip, and after the iteration of htmlstream.Reader.Children, the current token is the end tag, which must be passed to Pop too. htmlstream.Reader.Find skips end tags, so Stack can't be used with it.
Example ¶
A Stack keeps a value for the open elements, here the language of the text from the lang attributes.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<html lang=en><p>Hello, <span lang=fr>bonjour <b>le monde</b></span>!<p lang="">Unknown`
r := htmlstream.NewReader(strings.NewReader(page))
var lang htmlutil.Stack[string]
for r.Next() {
tok := r.Token()
switch tok.Kind() {
case htmlstream.StartTag:
if a, ok := tok.Attr("lang"); ok {
lang.Push(tok, a.Value())
}
case htmlstream.EndTag:
lang.Pop(tok)
case htmlstream.Text:
l, ok := lang.Top()
if !ok || *l == "" {
fmt.Printf("%q (unknown)\n", tok.Raw())
} else {
fmt.Printf("%q (%s)\n", tok.Raw(), *l)
}
}
}
if err := r.Err(); err != nil {
panic(err)
}
}
Output: "Hello, " (en) "bonjour " (fr) "le monde" (fr) "!" (en) "Unknown" (unknown)
func (*Stack[T]) All ¶
All returns an iterator over the indexes (see Stack.At) and values, innermost first, like htmlstream.Reader.Stack.
func (*Stack[T]) At ¶
At returns the value at index i, where 0 is the outermost element. It panics if i is out of range [0, Len()).
func (*Stack[T]) Closes ¶
func (s *Stack[T]) Closes(tok *htmlstream.Token) bool
Closes reports whether the end tag tok closes the innermost element with a value.
func (*Stack[T]) Pop ¶
func (s *Stack[T]) Pop(tok *htmlstream.Token) (T, bool)
Pop pops the value for the element closed by the end tag tok, if it is the innermost element with a value.
func (*Stack[T]) Push ¶
func (s *Stack[T]) Push(tok *htmlstream.Token, v T) bool
Push pushes v for the element opened by the start tag tok. It returns false (and does nothing) if tok doesn't open an element, or opens an untracked element (see htmlstream.Token.Untracked), whose end tag can't be matched.
type TextBuilder ¶
type TextBuilder struct {
// contains filtered or unexported fields
}
TextBuilder collects text, collapsing runs of ASCII whitespace (see ascii.IsSpace) into single spaces and trimming leading and trailing whitespace. Non-breaking spaces are kept. Unlike CSS, which collapses spaces, tabs and line breaks, it also collapses form feeds. The zero value is an empty TextBuilder ready to use.
Example ¶
TextBuilder collects text from tokens, collapsing whitespace.
package main
import (
"fmt"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/htmlutil"
)
func main() {
const page = `<ul><li> One </li><li>Two<br>lines</li></ul>`
r := htmlstream.NewReader(strings.NewReader(page))
var b htmlutil.TextBuilder
for r.Next() {
tok := r.Token()
switch {
case tok.Kind() == htmlstream.Text:
b.WriteText(tok)
case htmlutil.IsTextBreak(tok):
b.Break()
}
}
if err := r.Err(); err != nil {
panic(err)
}
fmt.Printf("%q\n", b.String())
}
Output: "One Two lines"
func (*TextBuilder) Bytes ¶
func (t *TextBuilder) Bytes() []byte
Bytes returns the text. It is valid until the next change.
func (*TextBuilder) Write ¶
func (t *TextBuilder) Write(p []byte) (int, error)
Write appends text. It never returns an error, so a TextBuilder can be used as an io.Writer.
func (*TextBuilder) WriteString ¶
func (t *TextBuilder) WriteString(s string) (int, error)
WriteString appends text, like TextBuilder.Write.
func (*TextBuilder) WriteText ¶
func (t *TextBuilder) WriteText(tok *htmlstream.Token)
WriteText appends the decoded text of a Text or CDATA token (see htmlstream.Token.AppendText).
type TextOptions ¶
type TextOptions struct {
// KeepWhitespace keeps the text as it is, like the DOM's textContent:
// whitespace isn't collapsed, and no line breaks are added.
KeepWhitespace bool
// AltText includes the alt text of img and area elements (and image
// elements under HTML rules, which HTML parsers turn into img).
AltText bool
// Hidden includes the text in elements whose contents aren't rendered
// (see [InnerText]).
Hidden bool
// ChildrenOnly only includes text directly inside the element, not in
// descendant elements (like the DOM's HTMLScriptElement.text).
ChildrenOnly bool
// Max limits the length of the text in bytes, if positive. The rest of
// the element is skipped, and InnerText reports the truncation.
Max int
}
TextOptions configures InnerText.