您可以使用反射来遍历字段并转义字符串字段。例如:
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>"}
请注意,EscapeString
html包中有一个函数。无需自己实施。