json - 如何清理golang中的输入数据?

标签 json forms postgresql http go

我正试图在将提交的数据编码到指定的结构之前不久对输入进行清理。

这是我正在使用的模型。

type Post struct {
    Id               int       `json:"Id"`
    CreatedAt        time.Time `json:"CreatedAt"`
    UpdatedAt        time.Time `json:"UpdatedAt"`
    CreatorId        int       `json:"CreatorId"`
    Creator          *User
    Editors          []int  `json:"Editors"`
    Status           Status `json:"Status"`
    Title            string `json:"Title"`
    ShortDescription string `json:"ShortDescription"`
    Description      string `json:"Description"`
    Content          string `json:"Content"`
    Url              string `json:"Url"`
    Media            *Media
    Categories       []Category `json:"Categories"`
    Tags             []Tag      `json:"Tags"`
    MediaId          int        `json:"MediaId"`
    Keywords         string     `json:"Keywords"`
    Data             []string   `json:"Data"`
}

这里是一个可能提交的 JSON 数据的例子

{"Id":1,"CreatedAt":"2016-10-11T21:29:46.134+02:00","UpdatedAt":"0001-01-01T00:00:00Z","CreatorId":1,"Editors":null,"Status":1,"Title":"This is the title of the first post, to be changed.<script>alert()</script>","ShortDescription":"this is the short description of this post","Description":"","Content":"Contrary to popular belief Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC making it over 2000 years old. Richard McClintock","Url":"lorem-ipsum-first"}

ReadJSON 期间,我将如何最有效地清理上述 JSON 表单数据?在此过程中请求和数据插入之前,从而删除所有恶意代码,如 <script>alert()</script>. 所示? 如果有任何其他有用的信息,请询问,我很乐意添加。 谢谢

最佳答案

对于 HTML 清理,您可以尝试 github.com/microcosm-cc/bluemonday .

用于根据您设置的规则验证 JSON 输入数据。

article是关于该主题的好读物。

文章中的示例。

type User struct {
     Name string    `json:"name"    validate:"nonzero"`
     Age uint       `json:"age"     validate:"min=1"`
     Address string `json:"address" validate:"nonzero"`
}

用于验证的包是gopkg.in/validator.v2

用法:

user := &models.User{}
if err = c.ReadJSON(user); err != nil {
    // Handle Error
}

p := bluemonday.UGCPolicy()
user.Name, user.Address = p.Sanitize(user.Name),p.Sanitize(user.Address)

if err = validator.Validate(user); err != nil {
   // Handle Error
}

err = db.Create(&user)
if err != nil {
    // Handle Error
}

关于json - 如何清理golang中的输入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140044/

相关文章:

javascript - Json - 创建一个自动递增的 ID 列

json - 在 JSON/XML 属性中使用多个命名空间分隔符是否可以接受?

javascript - Twitter Bootstrap 2 模式表单对话框

sql - 将角色一天中的时间更改为 Postgres 中的日期?

c# - 在 SQL 中克隆带有主键的行?

javascript - 为什么这个 for in 语句返回 0 和 1?

php - 使用 PHP 将 CSV 转换为 JSON?

c# - IntPtr.operator +(IntPtr,int)无法调用运算符或访问器

jquery - $ ("form").submit(function() { 在 Firefox 中不起作用

postgresql - Heroku PostgreSQL : Restart adds duplicate lines