binding

package module
v0.0.0-...-f86db18 Latest Latest
Warning

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

Go to latest
Published: May 26, 2017 License: Apache-2.0 Imports: 12 Imported by: 12

README

binding CircleCI

Middlware binding provides request data binding and validation for Tango.

Installation

go get github.com/tango-contrib/binding

Example

import (
    "github.com/lunny/tango"
    "github.com/tango-contrib/binding"
)

type Action struct {
    binding.Binder
}

type MyStruct struct {
    Id int64
    Name string
}

func (a *Action) Get() string {
    var mystruct MyStruct
    errs := a.Bind(&mystruct)
    return fmt.Sprintf("%v, %v", mystruct, errs)
}

func main() {
    t := tango.Classic()
    t.Use(binding.Bind())
    t.Get("/", new(Action))
    t.Run()
}

Visit /?id=1&name=2 on your browser and you will find output

{1 sss}, []

Getting Help

Credits

This package is forked from macaron-contrib/binding with modifications.

License

This project is under Apache v2 License. See the LICENSE file for the full license text.

Documentation

Overview

Package binding is a middleware that provides request data binding and validation for Macaron.

Index

Constants

View Source
const (
	// Type mismatch errors.
	ERR_CONTENT_TYPE    = "ContentTypeError"
	ERR_DESERIALIZATION = "DeserializationError"
	ERR_INTERGER_TYPE   = "IntegerTypeError"
	ERR_BOOLEAN_TYPE    = "BooleanTypeError"
	ERR_FLOAT_TYPE      = "FloatTypeError"

	// Validation errors.
	ERR_REQUIRED       = "RequiredError"
	ERR_ALPHA_DASH     = "AlphaDashError"
	ERR_ALPHA_DASH_DOT = "AlphaDashDotError"
	ERR_MIN_SIZE       = "MinSizeError"
	ERR_MAX_SIZE       = "MaxSizeError"
	ERR_RANGE          = "RangeError"
	ERR_EMAIL          = "EmailError"
	ERR_URL            = "UrlError"
	ERR_IN             = "InError"
	ERR_NOT_INT        = "NotInError"
	ERR_INCLUDE        = "IncludeError"
	ERR_EXCLUDE        = "ExcludeError"
	ERR_DEFAULT        = "DefaultError"
)
View Source
const (
	STATUS_UNPROCESSABLE_ENTITY = 422
)

Variables

View Source
var MaxMemory = int64(1024 * 1024 * 10)

Maximum amount of memory to use when parsing a multipart form. Set this to whatever value you prefer; default is 10 MB.

Functions

func AddRule

func AddRule(r *Rule)

AddRule adds new validation rule.

func Bind

func Bind(options ...Options) tango.HandlerFunc

Validate is middleware to enforce required fields. If the struct passed in implements Validator, then the user-defined Validate method is executed, and its errors are mapped to the context. This middleware performs no error handling: it merely detects errors and maps them.

func SetNameMapper

func SetNameMapper(nm NameMapper)

SetNameMapper sets name mapper.

func Version

func Version() string

Types

type Binder

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

func (Binder) Bind

func (vd Binder) Bind(obj interface{}) Errors

func (*Binder) Json

func (vd *Binder) Json(jsonStruct interface{}) Errors

Json is middleware to deserialize a JSON payload from the request into the struct that is passed in. The resulting struct is then validated, but no error handling is actually performed here. An interface pointer can be added as a second argument in order to map the struct to a specific interface.

func (Binder) MapForm

func (vd Binder) MapForm(obj interface{}) Errors

Form is middleware to deserialize form-urlencoded data from the request. It gets data from the form-urlencoded body, if present, or from the query string. It uses the http.Request.ParseForm() method to perform deserialization, then reflection is used to map each field into the struct with the proper type. Structs with primitive slice types (bool, float, int, string) can support deserialization of repeated form keys, for example: key=val1&key=val2&key=val3 An interface pointer can be added as a second argument in order to map the struct to a specific interface.

func (Binder) MultipartForm

func (vd Binder) MultipartForm(obj interface{}) Errors

MultipartForm works much like Form, except it can parse multipart forms and handle file uploads. Like the other deserialization middleware handlers, you can pass in an interface to make the interface available for injection into other handlers later.

func (*Binder) SetBinder

func (vd *Binder) SetBinder(req *http.Request)

func (Binder) Validate

func (vd Binder) Validate(obj interface{}) Errors

type Bindinger

type Bindinger interface {
	SetBinder(*http.Request)
}

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"`
}

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. This type is mapped to the context so you can inject it into your own handlers and use it in your application if you want all your errors to look the same.

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) ErrorMap

func (e *Errors) ErrorMap() map[string]Error

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 NameMapper

type NameMapper func(string) string

NameMapper represents a form/json tag name mapper.

type Options

type Options struct {
}

type Rule

type Rule struct {
	// IsMatch checks if rule matches.
	IsMatch func(string) bool
	// IsValid applies validation rule to condition.
	IsValid func(Errors, string, interface{}) bool
}

Rule represents a validation rule.

type RuleMapper

type RuleMapper []*Rule

RuleMapper represents a validation rule mapper, it allwos users to add custom validation rules.

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 is the interface that handles some rudimentary request validation logic so your application doesn't have to.

Jump to

Keyboard shortcuts

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