So you want to parse a form. You have your handler, and you’re getting data passed in through the request.
The next step is to parse the form on the request.
This will populate
r.Form. From here, we can use gorilla’s schema package to decode the form values onto a instantiated struct.
There are several things to notice here. The first is the
IgnoreUnknownKeys setting. I can see where the creators of the schema package were attempting to prevent users from not explicitly handling portions of a form, but found that not knowing this setting was a severe disadvantage when writing a resusable handler across multiple forms. I wasted so much time trying to figure out how to avoid having to state all entries of all the forms it would ever encounter when I was writing a general recaptcha handler (it doesn’t need the other values in order to do its job before moving on to the child handler). All this to say that this setting is important enough that it should be at least bolded in the docs.
The second thing to notice is that I ignore the recommendation by the creators of the package to define the decoder globally. I feel that this makes the code harder to read than instantiating a decoder individually, especially if you have an extremely large file.
This may all seem familiar to you. You might be asking: why should I use this method instead of the
json package with
The key to this question lies on the data type we are being sent. By accessing the header data in the request via
r.Header.Get("Content-Type"), and determine whether we are being sent form URL encoded data, or json. The gorilla
decode package is used for
PUTs) of URL encoded data, while unmarshaling works for json. If you are unsure of which data type you’re being passed, you may add a switch statement to the beginning of the handler that checks the type before proceeding.
If you’re curious, according to MDN’s documentation, URL encoded is a bit like how it sounds: “the keys and values are encoded in key-value tuples separated by ‘&', with a ‘=’ between the key and the value”.
Now go forth and parse some forms!