2

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?

Sredny M Casanova
  • 4,735
  • 21
  • 70
  • 115
  • The best way to prevent xss is escape the value with correct escape function when the value is add to the html or javascript.Escape string in the input process will get wrong result when it output to other place like android. – bronze man Sep 17 '18 at 09:28

1 Answers1

4

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.

Dan Esparza
  • 28,047
  • 29
  • 99
  • 127
jussius
  • 3,114
  • 15
  • 21
  • Is it possible to make this a function that can accept any struct and sanitize it? The absence of generics in Go confuses me... – Vasilije Bursac Jun 12 '21 at 11:21