2017-05-26 13:29
浏览 465


I am using Golang to construct an API Rest. I have a struct with a lot of fields (more than 100), so I assign the values that comes from the client side to the struct using gorilla/schema that's working pretty nice.

Now, I want to avoid the users to insert Javascript code in any of the strings fields, in the struct I have defined bool, strings, byte[] and int values. So, now I am wondering what is the best way to validate that.

I am thinking in interate over the struct only in the strings fields and make something like:

Loop over the struct {
     myProperty := JSEscapeString(myProperty)

Is it ok? in that case, how can I loop over the struct but only the string fields?

图片转代码服务由CSDN问答提供 功能建议

我正在使用Golang构造API Rest。 我有一个结构,其中包含很多字段(超过100个),所以我使用很好的 gorilla / schema 将来自客户端的值分配给该结构。 \ n

现在,我要避免用户在任何字符串字段中插入Javascript代码,在结构中我定义了bool,strings,byte []和int值。 所以,现在,我想知道什么是验证此方法的最佳方法。


 myProperty:= JSEscapeString(myProperty)

可以吗? 在这种情况下,我该如何遍历该结构,而仅遍历字符串字段?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dopmgo4707 2017-05-26 14:24

    You can use reflection to loop over the fields and escape the string fields. For example:

    myStruct := struct {
            IntField int
            StringField string
        } {
            IntField: 42,
            StringField: "<script>alert('foo');</script>",
        value := reflect.ValueOf(&myStruct).Elem()
        // loop over the struct
        for i := 0; i < value.NumField(); i++ {
            field := value.Field(i)
            // check if the field is a string
            if field.Type() != reflect.TypeOf("") {
            str := field.Interface().(string)
            // set field to escaped version of the string
        fmt.Printf("%#v", myStruct)
        // prints: struct { IntField int; StringField string }{IntField:42, StringField:"&lt;script&gt;alert(&#39;foo&#39;);&lt;/script&gt;"}

    Note that there's an EscapeString function in the html package. No need to implement your own.

    点赞 打赏 评论

相关推荐 更多相似问题