Skip to content

反 XSS

系统自带 XSS 代码清理功能,您可以通过为结构体定义 xss tag + bindx.ShouldBindTri 公共函数来使用,示例如下:

go
package model

type Test struct {
    // xss:"text" 表示清理所有 HTML 标签
	String string `gorm:"comment:字符串;type:text" json:"string" xss:"text"`
    // xss:"html" 表示尽量保留 HTML 标签,但清理里边的所有 XSS 代码
	Editor string `gorm:"comment:富文本;type:text" json:"editor" xss:"html"`
}
go
// 调用 bindx.ShouldBindTri,一句代码实现: 绑定值、做数据验证、清理 XSS
var tri bindx.Tri[model.Test]
if err := bindx.ShouldBindTri(body, &tri); err != nil {
    httpx.Fail(c, httpx.WithMessage("参数错误: "+err.Error()))
    return
}

// 已清理掉 XSS 代码的 Editor 字段值
tri.Model.Editor

// 已清理掉 HTML 代码的 String 字段值
tri.Model.String

// 根据 ShouldBindTri 的特性,Map 的值来自 Model,所以以下两个字段也已经清理过了,若有指定 DTO 也一样
tri.Map["Editor"]
tri.Map["String"]

TIP

  1. 反 XSS 基于 github.com/microcosm-cc/bluemonday 实现。
  2. 封装于 pkg\xss\xss.go 文件,您还可以直接使用该包的 HTMLPolicySanitizeTextPolicySanitizeSanitizeStruct 公开函数。