douweinu8562 2017-05-26 13:29
浏览 641
已采纳

在Golang中实施XSS保护

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?

  • 写回答

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("") {
                continue
            }
    
            str := field.Interface().(string)
            // set field to escaped version of the string
            field.SetString(html.EscapeString(str))
        }
    
        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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!