如何在golang中对输入数据进行消毒处理?

10

我试图在将提交的数据编组到指定的结构体之前,尽可能净化输入。

这是我使用的模型。

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>一样。

如果有任何其他可以使用的信息,请告诉我,我很乐意添加它。

谢谢


5
你可能应该阅读这篇文章:为什么你不应该在Go项目中使用iris。我并不是说你一定要转换,但至少要了解社区中许多人对Iris的担忧。 - joshlf
3
实际上,在Go语言中完全没有必要使用一个框架,这正是我最喜欢Go的地方。 - Yandry Pozo
至少我现在发现了,而不是以后。 - Colleen Larsen
感谢您分享这篇文章和您的建议。 - Colleen Larsen
1个回答

16
对于HTML清理,你可以尝试使用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
}

3
谢谢你的回答!还有非常好的验证文章,我的确想确保没有危险的输入被插入到数据库中,因此我需要在验证过程之上清理(消毒)插入的参数,尤其是因为我将处理HTML插入。再次感谢您的回答! - Colleen Larsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接