您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Golang中实施XSS保护

在Golang中实施XSS保护

您可以使用反射来遍历字段并转义字符串字段。例如:

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;"}

请注意,EscapeStringhtml包中有一个函数。无需自己实施。

Go 2022/1/1 18:17:43 有603人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶