binding

package module
Version: v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2016 License: MIT Imports: 8 Imported by: 65

README

binding is reflectionless data binding for Go

binding

Reflectionless data binding for Go's net/http

Features

  • HTTP request data binding
  • Data validation (custom and built-in)
  • Error handling

Benefits

  • Moves data binding, validation, and error handling out of your application's handler
  • Reads Content-Type to deserialize form, multipart form, and JSON data from requests
  • No middleware: just a function call
  • Usable in any setting where net/http is present (Negroni, gocraft/web, std lib, etc.)
  • No reflection

Usage example

package main

import (
	"fmt"
	"net/http"

	"github.com/mholt/binding"
)

// First define a type to hold the data
// (If the data comes from JSON, see: http://mholt.github.io/json-to-go)
type ContactForm struct {
	User struct {
		ID int
	}
	Email   string
	Message string
}

// Then provide a field mapping (pointer receiver is vital)
func (cf *ContactForm) FieldMap(req *http.Request) binding.FieldMap {
	return binding.FieldMap{
		&cf.User.ID: "user_id",
		&cf.Email:   "email",
		&cf.Message: binding.Field{
			Form:     "message",
			Required: true,
		},
	}
}

// Now your handlers can stay clean and simple
func handler(resp http.ResponseWriter, req *http.Request) {
	contactForm := new(ContactForm)
	errs := binding.Bind(req, contactForm)
	if errs.Handle(resp) {
		return
	}
	fmt.Fprintf(resp, "From:    %d\n", contactForm.User.ID)
	fmt.Fprintf(resp, "Message: %s\n", contactForm.Message)
}

func main() {
	http.HandleFunc("/contact", handler)
	http.ListenAndServe(":3000", nil)
}

Multipart/form-data usage example

package main

import (
	"bytes"
	"fmt"
	"github.com/mholt/binding"
	"io"
	"log"
	"mime/multipart"
	"net/http"
)

// We expect a multipart/form-data upload with
// a file field named 'data'
type MultipartForm struct {
	Data *multipart.FileHeader `json:"data"`
}

func (f *MultipartForm) FieldMap(req *http.Request) binding.FieldMap {
	return binding.FieldMap{
		&f.Data: "data",
	}
}

// Handlers are still clean and simple
func handler(resp http.ResponseWriter, req *http.Request) {
	multipartForm := new(MultipartForm)
	errs := binding.Bind(req, multipartForm)
	if errs.Handle(resp) {
		return
	}

	// To access the file data you need to Open the file
	// handler and read the bytes out.
	var fh io.ReadCloser
	var err error
	if fh, err = multipartForm.Data.Open(); err != nil {
		http.Error(resp,
			fmt.Sprint("Error opening Mime::Data %+v", err),
			http.StatusInternalServerError)
		return
	}
	defer fh.Close()
	dataBytes := bytes.Buffer{}
	var size int64
	if size, err = dataBytes.ReadFrom(fh); err != nil {
		http.Error(resp,
			fmt.Sprint("Error reading Mime::Data %+v", err),
			http.StatusInternalServerError)
		return
	}
	// Now you have the attachment in databytes.
	// Maximum size is default is 10MB.
	log.Printf("Read %v bytes with filename %s",
		size, multipartForm.Data.Filename)
}

func main() {
	http.HandleFunc("/upload", handler)
	http.ListenAndServe(":3000", nil)
}

You can test from CLI using the excellent httpie client

http -f POST localhost:3000/upload data@myupload

Custom data validation

You may optionally have your type implement the binding.Validator interface to perform your own data validation. The .Validate() method is called after the struct is populated.

func (cf ContactForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
	if cf.Message == "Go needs generics" {
		errs = append(errs, binding.Error{
			FieldNames:     []string{"message"},
			Classification: "ComplaintError",
			Message:        "Go has generics. They're called interfaces.",
		})
	}
	return errs
}

Error Handling

binding.Bind() and each deserializer returns errors. You don't have to use them, but the binding.Errors type comes with a kind of built-in "handler" to write the errors to the response as JSON for you. For example, you might do this in your HTTP handler:

if binding.Bind(req, contactForm).Handle(resp) {
	return
}

As you can see, if .Handle(resp) wrote errors to the response, your handler may gracefully exit.

Binding custom types

For types you've defined, you can bind form data to it by implementing the Binder interface. Here's a contrived example:

type MyType map[string]string

func (t *MyType) Bind(fieldName string, strVals []string, errs binding.Errors) binding.Errors {
	t["formData"] = strVals[0]
	return errs
}

If you can't add a method to the type, you can still specify a Binder func in the field spec. Here's a contrived example that binds an integer (not necessary, but you get the idea):

func (t *MyType) FieldMap() binding.FieldMap {
	return binding.FieldMap{
		"number": binding.Field{
			Binder: func(fieldName string, formVals []string, errs binding.Errors) binding.Errors {
				val, err := strconv.Atoi(formVals[0])
				if err != nil {
					errs.Add([]string{fieldName}, binding.DeserializationError, err.Error())
				}
				t.SomeNumber = val
				return errs
			},
		},
	}
}

Notice that the binding.Errors type has a convenience method .Add() which you can use to append to the slice if you prefer.

Supported types (forms)

The following types are supported in form deserialization by default. (JSON requests are delegated to encoding/json.)

  • uint, *uint, []uint, uint8, *uint8, []uint8, uint16, *uint16, []uint16, uint32, *uint32, []uint32, uint64, *uint64, []uint64
  • int, *int, []int, int8, *int8, []int8, int16, *int16, []int16, int32, *int32, []int32, int64, *int64, []int64
  • float32, *float32, []float32, float64, *float64, []float64
  • bool, *bool, []bool
  • string, *string, []string
  • time.Time, *time.Time, []time.Time
  • *multipart.FileHeader, []*multipart.FileHeader

Documentation

Overview

Package binding deserializes data from HTTP requests into a struct ready for your application to use (without reflection). It also facilitates data validation and error handling.

Index

Constants

View Source
const (
	RequiredError        = "RequiredError"
	ContentTypeError     = "ContentTypeError"
	DeserializationError = "DeserializationError"
	TypeError            = "TypeError"
)
View Source
const (
	StatusUnprocessableEntity = 422
)

Variables

View Source
var (
	// Maximum amount of memory to use when parsing a multipart form.
	// Set this to whatever value you prefer; default is 10 MB.
	MaxMemory = int64(1024 * 1024 * 10)

	// If no TimeFormat is specified for a time.Time field, this
	// format will be used by default when parsing.
	TimeFormat = time.RFC3339
)

Functions

This section is empty.

Types

type Binder

type Binder interface {
	// Bind populates the type with data in []string which comes from the
	// HTTP request. The first argument is the field name.
	Bind(string, []string, Errors) Errors
}

Binder is an interface which can deserialize itself from a slice of string coming from the request. Implement this interface so the type can be populated from form data in HTTP requests.

type Error

type Error struct {
	// An error supports zero or more field names, because an
	// error can morph three ways: (1) it can indicate something
	// wrong with the request as a whole, (2) it can point to a
	// specific problem with a particular input field, or (3) it
	// can span multiple related input fields.
	FieldNames []string `json:"fieldNames,omitempty"`

	// The classification is like an error code, convenient to
	// use when processing or categorizing an error programmatically.
	// It may also be called the "kind" of error.
	Classification string `json:"classification,omitempty"`

	// Message should be human-readable and detailed enough to
	// pinpoint and resolve the problem, but it should be brief. For
	// example, a payload of 100 objects in a JSON array might have
	// an error in the 41st object. The message should help the
	// end user find and fix the error with their request.
	Message string `json:"message,omitempty"`
}

Error is a powerful implementation of the built-in error interface that allows for error classification, custom error messages associated with specific fields, or with no associations at all.

func (Error) Error

func (e Error) Error() string

Error returns this error's message.

func (Error) Fields

func (e Error) Fields() []string

Fields returns the list of field names this error is associated with.

func (Error) Kind

func (e Error) Kind() string

Kind returns this error's classification.

type Errors

type Errors []Error

Errors may be generated during deserialization, binding, or validation. It implements the built-in error interface.

func Bind

func Bind(req *http.Request, userStruct FieldMapper) Errors

Bind takes data out of the request and deserializes into a struct according to the Content-Type of the request. If no Content-Type is specified, there better be data in the query string, otherwise an error will be produced.

func Form

func Form(req *http.Request, userStruct FieldMapper) Errors

Form deserializes form data out of the request into a struct you provide. This function invokes data validation after deserialization.

func Json

func Json(req *http.Request, userStruct FieldMapper) Errors

Json deserializes a JSON request body into a struct you specify using the standard encoding/json package (which uses reflection). This function invokes data validation after deserialization.

func MultipartForm

func MultipartForm(req *http.Request, userStruct FieldMapper) Errors

MultipartForm reads a multipart form request and deserializes its data and files into a struct you provide. Files should be deserialized into *multipart.FileHeader fields.

func Validate

func Validate(errs Errors, req *http.Request, userStruct FieldMapper) Errors

Validate ensures that all conditions have been met on every field in the populated struct. Validation should occur after the request has been deserialized into the struct.

func (*Errors) Add

func (e *Errors) Add(fieldNames []string, classification, message string)

Add adds an error associated with the fields indicated by fieldNames, with the given classification and message.

func (Errors) Error

func (e Errors) Error() string

Error returns a concatenation of all its error messages.

func (Errors) Handle

func (e Errors) Handle(response http.ResponseWriter) bool

Handle writes the errors to response in JSON form if any errors are contained, and it will return true. Otherwise, nothing happens and false is returned. (The value receiver is due to issue 8: https://github.com/mholt/binding/issues/8)

func (*Errors) Has

func (e *Errors) Has(class string) bool

Has determines whether an Errors slice has an Error with a given classification in it; it does not search on messages or field names.

func (*Errors) Len

func (e *Errors) Len() int

Len returns the number of errors.

type Field

type Field struct {

	// Form is the form field name to bind from
	Form string

	// Required indicates whether the field is required. A required
	// field that deserializes into the zero value for that type
	// will generate an error.
	Required bool

	// TimeFormat specifies the time format for time.Time fields.
	TimeFormat string

	// Binder is a function that converts the incoming request value(s)
	// to the field type; in other words, this field is populated
	// by executing this function. Useful when the custom type doesn't
	// implement the Binder interface.
	Binder func(string, []string, Errors) Errors

	//A custom error message
	ErrorMessage string
}

Field describes the properties of a struct field.

type FieldMap

type FieldMap map[interface{}]interface{}

FieldMap is a map of pointers to struct fields -> field names from the request. The values could also be Field structs to specify metadata about the field.

type FieldMapper

type FieldMapper interface {
	// FieldMap returns a map of pointers into which the values will
	// be deserialized to field names from the request's form body.
	FieldMap(*http.Request) FieldMap
}

Only types that are FieldMappers can have request data deserialized into them.

type Validator

type Validator interface {
	// Validate validates that the request is OK. It is recommended
	// that validation be limited to checking values for syntax and
	// semantics, enough to know that you can make sense of the request
	// in your application. For example, you might verify that a credit
	// card number matches a valid pattern, but you probably wouldn't
	// perform an actual credit card authorization here.
	Validate(*http.Request, Errors) Errors
}

Validator can be implemented by your type to handle some rudimentary request validation separately from your application logic.

Jump to

Keyboard shortcuts

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