繁体   English   中英

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

[英]How to sanitize input data in golang?

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

这是我正在使用的模型。

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>.看到的任何恶意代码<script>alert()</script>. ? 如果有任何可能有用的其他信息,请询问,我很乐意添加它。 谢谢

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

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

这篇文章是关于这个主题的好读物。

文章中的一个例子。

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM