formdata

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2021 License: MIT Imports: 5 Imported by: 0

README

formdata

GoDoc

formdata is a simple and idomatic Go library for multipart/form-data.

The main focus for this library is parsing, validating and accessing form-data from HTTP requests. The core element of this libary is FormData, which wraps the multipart.Form object and adds additional validation capabilities.

Validation is written to enable chaining and therefore improve code readability.

Features

  • Parsing - Directly parsing http.Requests into FormData. A wrapper which extends multipart.Form with additional validation capabilities.

  • Chainability - Easy and intuative validation with chainable functions (examples below).

  • Independent - No external dependencies besides the Go standard library, meaning it won't bloat your project.

  • Documentation - With real world examples.

Install

go get -u github.com/neox5/go-formdata

Usage

Example shows how formdata helps handling a request for an email endpoint:

func (s *Server) handleMailRequestV1() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
    // set http.MaxBytesReader before parsing to limit the size of the incoming
    // request.
    r.Body = http.MaxBytesReader(w, r.Body, formdata.DefaultParseMaxMemory) // 1MiB

    // PARSE formdata from request
    fd, err := formdata.Parse(r)
    if err == formdata.ErrNotMultipartFormData {
      // ...handle unsupported media type
      return
    }
    if err != nil {
      // ...handle internal server error
      return
    }

    // VALIDATE formdata
    fd.Validate("from").Required().HasN(1)
    fd.Validate("subject").Required().HasN(1)
    fd.Validate("body").Required().HasN(1)
    fd.Validate("to").Required().HasNMin(1).MatchAllEmail()

    if fd.HasErrors() {
      message := fmt.Sprintf("validation errors: %s", strings.Join(fd.Errors(), "; "))
      // ...handle bad request
      return
    }

    // ACCESS formdata values
    from := fd.Get("from").First()
    subject := fd.Get("subject").First()
    body := fd.Get("body").First()

    msg := NewMail(from, subject, body)

    to := fd.Get("to")

    for _, recipient := range to {
      msg.AddRecipient(recipient)
    }

    if fd.FileExists("attachment") {
      for _, file := range fd.GetFile("attachment") {
        reader, err := file.Open()
        if err != nil {
          // ...handle invalid attachment
          return
        }
        msg.AddReaderAttachment(file.Filename, reader)
      }
    }

    s.sendMessage(msg)
  }
}

Parsing

Methods
  • Parse - envokes ParseMax(r, DefaultParseMaxMemory), DefaultParseMaxMemory = 1MiB

  • ParseMax - parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its files parts are stored in memory, with the rmainder stored on disk in temporary files.

FormData

FormData is the central element of formdata and it is returned from either Parse or ParseMax.

// FormData extends multipart.Form with additional validation capabilities.
type FormData struct {
	*multipart.Form
	errors []*ValidationError
}
FormData Methods
  • Validate - returns a Value Validation on the given key
  • ValidateFile - returns a File Validation on the given key
  • HasErrors - checks if FormData has validation errors
  • Errors - returns validation errors as []string
  • Exists - checks if key exists in FormData.Value
  • FileExists - checks if key exists in FormData.File
  • Get - returns FormDataValue for given key
  • GetFile - returns FormDataFile for given key

Validation

Global Validation
  • Required - add required validation, checks if key exists in FormData
  • HasN - checks if Value/File has N elements
  • HasNMin - cheks if Value/File has minimum N elements
Value Validation
  • Match - validates if the first element matches a regular expression
  • MatchAll - validates if all elements match a given regular expression
  • MatchEmail - validates if the first element matches an email
  • MatchAllEmail - validates if all elements are matching an email
File Validation

...still loading

FormDataValue

FormDataValue is the returned type of the Get method on the FormData type.

Methods
  • At - gets element of FormDataValue at the given index
  • First - gets the first element of FormDataValue

FormDataFile

FormDataFile is the returned type of the GetFile method on the FormData type.

Methods
  • At - gets element of FormDataFile at the given index
  • First - gets the first element of FormDataFile

Inspiration

This library is conceptually similar to albrow/forms, with the following major behavioral differences:

  • Focusing only on multipart/form-data.
  • Wrapping multipart.Form without redefining a new data struct.
  • Support for chainable validation.
  • Support for multiple files per key.

License

formdata is licensed under the MIT License. See the LICENSE file for more information.

Documentation

Overview

Package formdata provides helpers for multipart/form-data requests with no external dependencies.

The main focus for this library is parsing, validating and accessing form-data from HTTP requests. The core element of this libary is FormData, which wraps the multipart.Form object and adds additional validation capabilities.

Validation is written to enable chaining and therefore improve code readability.

Index

Constants

View Source
const (
	// DefaultParseMaxMemory is the default maxMemory value for
	// ParseMultipartForm used by the Parse method.
	DefaultParseMaxMemory int64 = 2 << 19 // 1 MiB = 1,048,576 Bytes
)

Variables

View Source
var (
	// ErrNotMultipartFormData is returned by the Parse method to indicate that
	// the parsed request has a differnt Content-Type than multipart/form-data.
	ErrNotMultipartFormData = &FormDataError{"request Content-Type isn't multipart/form-data"}
)

Functions

This section is empty.

Types

type FormData

type FormData struct {
	*multipart.Form
	// contains filtered or unexported fields
}

FormData extends multipart.Form with additional validation capabilities.

func Parse

func Parse(r *http.Request) (*FormData, error)

Parse envokes ParseMax(r, DefaultParseMaxMemory).

func ParseMax

func ParseMax(r *http.Request, maxMemory int64) (*FormData, error)

ParseMax parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files.

To limit the size of the incoming request set http.MaxBytesReader before parsing.

func (*FormData) Errors

func (fd *FormData) Errors() []string

Errors returns validation errors as []string. If there are no validation errors an empty []string is returned.

func (*FormData) Exists

func (fd *FormData) Exists(key string) bool

Exists checks if FormData.Value has given key.

func (*FormData) FileExists

func (fd *FormData) FileExists(key string) bool

FileExists checks if FormData.File has given key.

func (*FormData) Get

func (fd *FormData) Get(key string) FormDataValue

Get gets the value array associated with the given key. If there are no values associated with the key, Get returns an empty []string.

func (*FormData) GetFile

func (fd *FormData) GetFile(key string) FormDataFile

GetFile returns the *multipart.FileHeader array associated with the given key. If there are no value associated with the key, GetFile returns an empty []*multipart.FileHeader.

func (*FormData) HasErrors

func (fd *FormData) HasErrors() bool

HasErrors checks if form-data has any validation errors.

func (*FormData) Validate

func (fd *FormData) Validate(key string) *Validation

Validate creates a field validation from a given form-data key.

func (*FormData) ValidateFile

func (fd *FormData) ValidateFile(key string) *Validation

ValidateFile creates a file validation from a given form-data key.

type FormDataError

type FormDataError struct {
	ErrorString string
}

FormDataError represents an error working with multipart/form-data.

func (*FormDataError) Error

func (fe *FormDataError) Error() string

type FormDataFile

type FormDataFile []*multipart.FileHeader

FormDataFile is the value of an element in FormData.File.

func (FormDataFile) At added in v0.1.0

func (f FormDataFile) At(index int) *multipart.FileHeader

At returns a single *multipart.FileHeader of FormDataFile at the given index. If index is out of bound nil is returned.

func (FormDataFile) First added in v0.1.0

func (f FormDataFile) First() *multipart.FileHeader

First envokes FormDataFile.

type FormDataValue

type FormDataValue []string

FormDataValue is the value of an element in multipart.Form.Value.

func (FormDataValue) At

func (v FormDataValue) At(index int) string

At gets one element of FormDataValue at the given index. If index is out of bound an empty string is returned.

func (FormDataValue) First

func (v FormDataValue) First() string

First envokes FormDataValue.GetAt(0).

type Validation

type Validation struct {
	// contains filtered or unexported fields
}

func (*Validation) HasN

func (v *Validation) HasN(count int) *Validation

HasN validates if a value has the given number of elements.

func (*Validation) HasNMin

func (v *Validation) HasNMin(count int) *Validation

HasNMin validates if a value has minimal N number of elements.

func (*Validation) Match

func (v *Validation) Match(regex *regexp.Regexp) *Validation

Match validates if the first element of the value matches the given regular expression.

func (*Validation) MatchAll

func (v *Validation) MatchAll(regex *regexp.Regexp) *Validation

MatchAll validates if all elements of the value matching the given regular expresssion.

func (*Validation) MatchAllEmail

func (v *Validation) MatchAllEmail() *Validation

MatchAllEmail validates if all elements of the value matching an email.

func (*Validation) MatchEmail

func (v *Validation) MatchEmail() *Validation

MatchEmail validates if the first element of the value matches an email.

func (*Validation) Required

func (v *Validation) Required() *Validation

Required checks if a key exists in the form-data

type ValidationError

type ValidationError struct {
	// contains filtered or unexported fields
}

func (ValidationError) String

func (ve ValidationError) String() string

Directories

Path Synopsis
tools module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL