Implement XSS protection in Golang

白昼怎懂夜的黑 提交于 2020-04-12 07:01:32

问题


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:


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.



来源:https://stackoverflow.com/questions/44202894/implement-xss-protection-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!