在 Golang 中实现 XSS 保护
Implement XSS protection in Golang
我正在使用 Golang 构建一个 API Rest。我有一个包含很多字段(超过 100 个)的结构,所以我使用 gorilla/schema
将来自客户端的值分配给该结构,效果非常好。
现在,我想避免用户在任何字符串字段中插入 Javascript 代码,在我定义了 bool、strings、byte[] 和 int 值的结构中。所以,现在我想知道验证这一点的最佳方法是什么。
我正在考虑仅在字符串字段中对结构进行交互,并制作如下内容:
Loop over the struct {
myProperty := JSEscapeString(myProperty)
}
可以吗?在那种情况下,我怎样才能遍历结构但只遍历字符串字段?
您可以使用反射来遍历字段并转义字符串字段。
例如:
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>"}
请注意 html 包中有一个 EscapeString
函数。无需自己实现。
我正在使用 Golang 构建一个 API Rest。我有一个包含很多字段(超过 100 个)的结构,所以我使用 gorilla/schema
将来自客户端的值分配给该结构,效果非常好。
现在,我想避免用户在任何字符串字段中插入 Javascript 代码,在我定义了 bool、strings、byte[] 和 int 值的结构中。所以,现在我想知道验证这一点的最佳方法是什么。
我正在考虑仅在字符串字段中对结构进行交互,并制作如下内容:
Loop over the struct {
myProperty := JSEscapeString(myProperty)
}
可以吗?在那种情况下,我怎样才能遍历结构但只遍历字符串字段?
您可以使用反射来遍历字段并转义字符串字段。 例如:
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>"}
请注意 html 包中有一个 EscapeString
函数。无需自己实现。