douweinu8562 2017-05-26 13:29
浏览 641
已采纳

在Golang中实施XSS保护

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条回答 默认 最新

  • dopmgo4707 2017-05-26 14:24
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛