Skip to content

Version 0.2

Pre-release
Pre-release
Compare
Choose a tag to compare
@albrow albrow released this 10 Jan 01:23
· 16 commits to master since this release

I added support for parsing and validating files in multipart requests!

Here's how it works. When calling Parse(), if 1) the request has a Content-Type header which identifies it as a multipart request and 2) there is one or more files provided in the body of the request, go-data-parser will automatically parse the files and add a representation of them to the resulting Data object.

Here's an example of how to validate and read the contents of a file:

func CreateUserHandler(res http.ResponseWriter, req *http.Request) {
    // Parse request data.
    userData, err := data.Parse(req)
    if err != nil {
        // Handle err
        // ...
    } 

    // Validate
    val := userData.Validator()
    // RequireFile requires a non-empty file with the given key/field name
    val.RequireFile("profileImage")
    // AcceptFileExts allows you to specify which filetype extensions are allowed,
    // if any other extension was used, it generates a nice-looking error
    val.AcceptFileExts("profileImage", "jpg", "png", "gif")

    if val.HasErrors() {
        // Write the errors to the response
        // Maybe this means formatting the errors as json
        // or re-rendering the form with an error message
        // ...
    }

    // Get the contents of the profileImage file
    imageBytes, err := userData.GetFileBytes("profileImage")
    if err != nil {
        // Handle err
    }
    // Now you can either copy the file over to your server using io.Copy,
    // upload the file to something like amazon S3, or do whatever you want
    // with it.
}

This release is not 100% backward compatible with previous releases, but it is close.

In order to facilitate parsing and validating multipart form files, I needed to change the underlying data structure for the Data object. Previously, it was an alias for url.Values. Now, it is a struct containing url.Values and a map of string to *multipart.FileHeader. This will only cause problems if you were accessing Data as a url.Values directly. If you are only using the Get, Add, and Delete family of methods, then nothing has changed.