pint

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

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

Go to latest
Published: Jul 3, 2015 License: MIT Imports: 7 Imported by: 1

README

pint

Pint is a tiny Go library that helps you handle input from HTTP requests.

Installation

go get -u github.com/jamal/pint

Usage

type UserRegistration struct {
    FirstName string `pint:"first_name"`
    LastName string `pint:"last_name"`
    Email string `pint:"email,format:email"`
    Password string `pint:"password"`
    Age int `pint:"age,min:13,max:199"`
}

func UserRegistrationHandler(w http.ResponseWriter, r *http.Request) {
    user := &UserRegistration{}
    err := pint.Parse(r, user)
    if err == pint.ErrValidate {
        fmt.Fprintf(w, "Validation error: %s", er.String())
        return
    }

    // ...
}
Custom Format handler

You can register a custom format handler using RegisterHandler.

type User struct {
    Name string `pint:"name"`
    Phone string `pint:"phone,format:phone"`
}

func formatPhone(val string) (string, error) {
	num, err := libphonenumber.Parse(val, "US")
	if err != nil {
		return "", &pint.ErrValidate{fmt.Sprintf("%s is not a valid phone number", val)}
	}
	return libphonenumber.Format(num, libphonenumber.INTERNATIONAL), nil
}

func init() {
    pint.RegisterHandler("phone", formatPhone)
}

License

Released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(r *http.Request, v interface{}) error

Parse will parse the http.Request form and look for v's fields. It uses http.FormValue internally. It will return an error if an invalid v is passed and an *ErrValidate if a validation error occurs. Use ErrValidate.String() when returning a validation error to the client.

func RegisterHandler

func RegisterHandler(name string, handler FormatHandler)

RegisterHandler can be used to register custom field validation. The name of the handler will be used in the struct tag for the validate key. For example, if you registered a "phone" validate handler, your struct tag would be `pint:"phone,validate:phone"`.

Types

type ErrValidate

type ErrValidate struct {
	Description string
}

ErrValidate is a custom error type returned by validation functions, the Error() format should only be used internally. Use ErrValidate.String() for an error that can be returned to the client.

func (*ErrValidate) Error

func (e *ErrValidate) Error() string

func (*ErrValidate) String

func (e *ErrValidate) String() string

type FormatHandler

type FormatHandler func(string) (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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