-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_test.go
85 lines (76 loc) · 1.72 KB
/
example_test.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// This file is for demonstration in godoc. For more examples, see the /examples directory.
package lolhtml_test
import (
"bytes"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/coolspring8/go-lolhtml"
)
func ExampleNewWriter() {
chunk := []byte("Hello, <span>World</span>!")
r := bytes.NewReader(chunk)
w, err := lolhtml.NewWriter(
// output to stdout
os.Stdout,
&lolhtml.Handlers{
ElementContentHandler: []lolhtml.ElementContentHandler{
{
Selector: "span",
ElementHandler: func(e *lolhtml.Element) lolhtml.RewriterDirective {
err := e.SetInnerContentAsText("LOL-HTML")
if err != nil {
log.Fatal(err)
}
return lolhtml.Continue
},
},
},
},
)
if err != nil {
log.Fatal(err)
}
// copy from the bytes reader to lolhtml writer
_, err = io.Copy(w, r)
if err != nil {
log.Fatal(err)
}
// explicitly close the writer and flush the remaining content
err = w.Close()
if err != nil {
log.Fatal(err)
}
// Output: Hello, <span>LOL-HTML</span>!
}
func ExampleRewriteString() {
output, err := lolhtml.RewriteString(
`<div><a href="http://example.com"></a></div>`,
&lolhtml.Handlers{
ElementContentHandler: []lolhtml.ElementContentHandler{
{
Selector: "a[href]",
ElementHandler: func(e *lolhtml.Element) lolhtml.RewriterDirective {
href, err := e.AttributeValue("href")
if err != nil {
log.Fatal(err)
}
href = strings.ReplaceAll(href, "http:", "https:")
err = e.SetAttribute("href", href)
if err != nil {
log.Fatal(err)
}
return lolhtml.Continue
},
},
},
},
)
if err != nil {
log.Fatal(err)
}
fmt.Println(output)
// Output: <div><a href="https://example.com"></a></div>
}