-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexample_test.go
90 lines (72 loc) · 2.42 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
86
87
88
89
90
package xss_test
import (
"fmt"
"github.com/feiin/go-xss"
"strings"
)
var x *xss.Xss = xss.NewXSS(xss.XssOption{})
func Example() {
source := "<div a=\"1\" b=\"2\" data-a=\"3\" data-b=\"4\">hello</div>"
html := xss.FilterXSS(source, xss.XssOption{})
fmt.Printf("%s\nconvert to:\n%s", source, html)
//To avoid passing options every time, you can also do it in a faster way by creating a NewXSS instance:
source = "<div a=\"1\" b=\"2\" data-a=\"3\" data-b=\"4\">hello</div>"
options := xss.XssOption{}
x := xss.NewXSS(options)
html = x.Process(source)
fmt.Printf("%s\nconvert to:\n%s", source, html)
}
func ExampleNew() {
source := "<a href=\"javascript:alert(/xss/)\" title=\"hi\">link</a>"
options := xss.XssOption{}
x := xss.NewXSS(options)
safeHtml := x.Process(source)
fmt.Printf("safeHtml:%s", safeHtml)
}
func ExampleOnIgnoreTagAttr() {
source := "<div a=\"1\" b=\"2\" data-a=\"3\" data-b=\"4\">hello</div>"
html := xss.FilterXSS(source, xss.XssOption{
OnIgnoreTagAttr: func(tag, name, value string, isWhiteAttr bool) *string {
if len(name) >= 5 && name[0:5] == "data-" {
ret := name + "=\"" + xss.EscapeAttrValue(value) + "\""
return &ret
}
return nil
},
})
fmt.Printf("%s\nconvert to:\n%s", source, html)
}
func ExampleOnIgnoreTag() {
source := "<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>"
html := xss.FilterXSS(source, xss.XssOption{
OnIgnoreTag: func(tag, html string, options xss.TagOption) *string {
if len(tag) >= 2 && tag[0:2] == "x-" {
return &html
}
return nil
},
})
fmt.Printf("%s\nconvert to:\n%s", source, html)
}
func ExampleParseHtmlImages() {
source := "<img src=\"img1\">a<img src=\"img2\">b<img src=\"img3\">c<img src=\"img4\">d"
var list []string
xss.FilterXSS(source, xss.XssOption{
OnTagAttr: func(tag, name, value string, isWhiteAttr bool) *string {
if tag == "img" && name == "src" {
list = append(list, value)
}
return nil
},
})
fmt.Printf("image list:\n%s", strings.Join(list, ","))
}
func ExampleFilterAllTags() {
source := "<strong>hello</strong><script>alert(/xss/);</script>end"
html := xss.FilterXSS(source, xss.XssOption{
WhiteList: map[string][]string{}, // 白名单为空,表示过滤所有标签
StripIgnoreTag: true, // 过滤所有非白名单标签的HTML
StripIgnoreTagBody: []string{"script"}, //script标签较特殊,需要过滤标签中间的内容
})
fmt.Printf("text: %s", html)
}