问题
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:"<script>alert('foo');</script>"}
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