golang HTML 白名单

golang HTML 白名单工具

java html 白名单工具

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package html

import "github.com/microcosm-cc/bluemonday"

func PreventXSS(html string) string {
	var policy = bluemonday.NewPolicy()
	policy.AllowStandardURLs()
	policy.AllowAttrs("href").OnElements("a")
	policy.AllowElements("p")
	policy.AllowElements("div")
	policy.AllowAttrs("src").OnElements("img")
	return policy.Sanitize(html)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package html

import (
	"fmt"
	"testing"
)

func Test_prevent_xss(t *testing.T ) {
	html  := PreventXSS(`
			<img src="http://www.baiducom/abc.png"
					onerror="console.log('error')"
					
			/>
			<div>dd</div>
			<section>ddd</section>
			<iframe src=""></iframe>
	`)
	fmt.Println(html)
}