chirp

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

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

Go to latest
Published: Jan 13, 2019 License: MIT Imports: 11 Imported by: 0

README

chirp

Travis Build Go Report Card GoDoc codecov MIT License

Request parser for chi router

go get -u github.com/vporoshok/chirp

Usage

There are two way to use this library. Parse as function or as middleware. Supported tags are path for chi router path parts, query for query parameters and json for body regardless of type (json / form). For json used standard encoding/json, for other parts it is trying to cast encoding.TextUnmarshaler and use it on success, otherwise used fmt.Sscan.

Parse
router := chi.NewRouter()
router.Put("/user/{id}/name", func(w http.ResponseWriter, r *http.Request) {
    var data struct {
        ID       uuid.UUID `path:"id"`
        Name     string    `json:"name"`
        Part     string    `query:"part"`
        Priority uint8     `json:"priority"`
        Null     string    `json:"-"`
        Hero     string
    }
    if err := chirp.Parse(r, &data); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    // work with data
})
Middleware

Middleware need a struct instance, not point to struct!

router := chi.NewRouter()
type Data struct {
    ID       uuid.UUID `path:"id"`
    Name     string    `json:"name"`
    Part     string    `query:"part"`
    Priority uint8     `json:"priority"`
    Null     string    `json:"-"`
    Hero     string
}
router.With(
    chirp.Middleware(Data{}, chirp.WithInterrupt(400)),
).Put("/user/{id}/name", func(w http.ResponseWriter, r *http.Request) {
    data := chirp.RequestFromContext(r.Context()).(Data)
    // use data
})

Be aware to use middleware only on part of route which contained all needed parts. For example, next code is wrong:

router := chi.NewRouter()
type Data struct {
    ID       uuid.UUID `path:"id"`
    Name     string    `json:"name"`
    Part     string    `query:"part"`
    Priority uint8     `json:"priority"`
    Null     string    `json:"-"`
    Hero     string
}
router.Use(chirp.Middleware(Data{}, chirp.WithInterrupt(400)))
router.Put("/user/{id}/name", func(w http.ResponseWriter, r *http.Request) {
    data := chirp.RequestFromContext(r.Context()).(Data)
    // data.ID always be empty
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(dst interface{}, options ...Option) func(next http.Handler) http.Handler

Middleware to inject request struct

For every request middleware create new instance of dst struct and parse request to it. Result will be added to request context as non-pointered value.

func Parse

func Parse(req *http.Request, dst interface{}) error

Parse request body, chi path parts and query parameters into dst

func RequestFromContext

func RequestFromContext(ctx context.Context) interface{}

RequestFromContext extract request struct instance from context

Types

type Error

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

Error of parsing field

func (Error) Cause

func (err Error) Cause() error

Cause implement errors.Causer interface

func (Error) Error

func (err Error) Error() string

Error implements error interface

func (Error) Field

func (err Error) Field() reflect.StructField

Field return field reflector

func (Error) Part

func (err Error) Part() string

Part of request with error (path | query | body)

func (Error) Source

func (err Error) Source() string

Source of parse

func (Error) Tag

func (err Error) Tag() string

Tag name or field name

If error has been occurred on json unmarshaling it return "*"

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configure Middleware

func WithInterrupt

func WithInterrupt(status int) Option

WithInterrupt interrupt on error with given status

func WithLogger

func WithLogger(logger *log.Logger) Option

WithLogger log parse request errors

func WithOnError

func WithOnError(cb func(*Error, http.ResponseWriter, *http.Request) bool) Option

WithOnError add an error handler

If handler return true, request might be interrupt immediate.

Jump to

Keyboard shortcuts

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