-
Notifications
You must be signed in to change notification settings - Fork 15
/
htmlRenderer.go
89 lines (76 loc) · 1.71 KB
/
htmlRenderer.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
86
87
88
89
package justext
import (
"fmt"
"log"
"strings"
"github.com/levigross/exp-html"
)
/**
This should be a separate package!
And it should be a Writer!
*/
var selfClosingTags = map[string]bool{
"area": true,
"base": true,
"basefont": true,
"br": true,
"hr": true,
"input": true,
"img": true,
"link": true,
"meta": true,
}
// nodesToString loops over a node tree and generate HTML string
// Should be moved into html/utils package
func nodesToString(node *html.Node) string {
var response string = ""
switch node.Type {
case html.TextNode:
response = html.EscapeString(strings.TrimSpace(node.Data))
case html.ElementNode, html.DoctypeNode:
var att string = ""
if len(node.Attr) > 0 {
for _, a := range node.Attr {
att = fmt.Sprintf("%s %s=\"%s\"", att, a.Key, a.Val)
}
}
if _, ok := selfClosingTags[node.Data]; ok {
return fmt.Sprintf("<%s%s>", node.Data, att)
}
var content string = ""
if len(node.Child) > 0 {
for _, n := range node.Child {
content = fmt.Sprintf("%s%s", content, nodesToString(n))
}
}
response = fmt.Sprintf("<%s%s>%s</%s>", node.Data, att, content, node.Data)
case html.DocumentNode:
if len(node.Child) > 0 {
for _, n := range node.Child {
response = nodesToString(n)
}
}
case html.CommentNode:
// ignore
default:
log.Printf("Unhandled node: %s", nodeTypeToString(node))
}
return response
}
func nodeTypeToString(n *html.Node) (t string) {
switch n.Type {
case html.ErrorNode:
t = "Error"
case html.TextNode:
t = "Text"
case html.DocumentNode:
t = "Document"
case html.ElementNode:
t = "Element"
case html.CommentNode:
t = "Comment"
case html.DoctypeNode:
t = "Doctype"
}
return t
}