httpparms

package module
v0.0.0-...-30c778d Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2016 License: BSD-3-Clause Imports: 6 Imported by: 0

README

httpparms GoDoc Build Status

Package httpparms provides helper functions and types to load the content of an HTTP request into a Go struct. It supports loading the query string parameters, the form-encoded body and the JSON-encoded body. If the struct implements the Validator interface, it also validates the values.

See the godoc for full documentation.

Installation

$ go get github.com/PuerkitoBio/httpparms

Use -u to update, -t to install test dependencies.

Example

type parmTest struct {
	S string
	I int    `schema:"-"`
	Q string `schema:"q" json:"q_value"`
}

func (pt *parmTest) Validate() error {
    if pt.S == "" {
        return errors.New("parameter `s` is required")
    }
	if pt.I > 2 {
		return errors.New("parameter `i` is too big")
	}
	return nil
}

var parser = &httpparms.Parser{
    // use github.com/gorilla/schema as form decoder
    Form: schema.NewDecoder().Decode,
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    var pt parmTest
    if err := parser.ParseQueryJSON(r, &pt); err != nil {
        // Optionally get the parameter names in error with
        // parms := parser.ParametersFromErr(err)
        // and use this in the error message.
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    // process the request with valid parameters...
}

License

The BSD 3-clause license, see LICENSE file.

Documentation

Overview

Package httpparms provides helper functions and types to load the content of an HTTP request into a Go struct. It supports loading the query string parameters, the form-encoded body and the JSON-encoded body. If the struct implements the "Validator" interface, it also validates the values.

It supports various form decoders and JSON unmarshalers. Common such packages that can be used for forms are:

  • github.com/go-playground/form (requires the FormDecoderAdapter)
  • github.com/gorilla/schema

Common packages that can be used for JSON are:

  • encoding/json in the standard library
  • pquerna/ffjson/ffjson

The package also provides support to extract parameter names that failed validation so that a useful error message can be given to the caller.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormDecoderAdapter

func FormDecoderAdapter(fn func(v interface{}, vals url.Values) error) func(interface{}, map[string][]string) error

FormDecoderAdapter is an adapter for form decoder functions that take an url.Values type instead of a map[string][]string.

Types

type Parser

type Parser struct {
	// Form is the function to use to decode form values from a map.
	// If it is nil, form decoding will fail with an error.
	Form func(v interface{}, vals map[string][]string) error

	// JSON is the function to use to unmarshal JSON from a
	// slice of bytes. If it is nil, json.Unmarshal from the
	// standard library is used.
	JSON func(data []byte, v interface{}) error

	// ParametersExtractor is the function that can extract parameter names
	// from an error. The error may be generated by the JSON unmarshaler,
	// the form decoder, or may be any custom error returned by the
	// parameters validation.  The function doesn't have to handle all
	// cases, it can return nil for errors it doesn't know about.
	// If it is nil, no parameters are extracted.
	ParametersExtractor func(err error) []string
	// contains filtered or unexported fields
}

Parser decodes request parameters into a struct and validates the values if the struct implements Validator.

If the Form, JSON and ParametersExtractor values used by the Parser are safe for concurrent use, then the Parser is also safe for concurrent use. This is typically the case when using the recommended decoders.

func (*Parser) ParametersFromErr

func (p *Parser) ParametersFromErr(err error) []string

ParametersFromErr returns the list of parameter names that triggered the error. This can be used to return a helpful error message to the caller. The parameter names are deduplicated and sorted. It tries to extract parameter names in the following order:

  • If the error implements a "Cause() error" method, it calls it and uses the returned error for the other steps.
  • If the error implements a "Parameter() string" method, it uses this value.
  • If the error implements a "Parameters() []string" method, it uses those values.
  • If the parser has a non-nil ParametersExtractor, it calls it and uses those values.
  • If there are no parameter names found at this point and the error implements the "WrappedErrors() []error" method, it calls it and applies the first 4 steps on each error, cumulating the return values.

This last step supports the common "multi-error" errors, as implemented by github.com/hashicorp/go-multierror.

func (*Parser) ParseJSON

func (p *Parser) ParseJSON(r *http.Request, dst interface{}) error

ParseJSON parses the body of the request as JSON and unmarshals it into dst. If dst is a Validator, Validate is called and its error returned. The body is parsed as JSON regardless of the content-type of the request.

func (*Parser) ParseQuery

func (p *Parser) ParseQuery(r *http.Request, dst interface{}) error

ParseQuery parses the query values and stores the values in dst. If dst is a Validator, Validate is called and its error returned.

func (*Parser) ParseQueryForm

func (p *Parser) ParseQueryForm(r *http.Request, dst interface{}) error

ParseQueryForm parses the Form parameters of r into dst. The parameters may be provided in the query string or in the form-encoded body. The dst value must be a pointer to a struct that contains fields matching the form parameters, possibly using `schema` struct tags. If dst is a Validator, Validate is called and its error returned.

func (*Parser) ParseQueryJSON

func (p *Parser) ParseQueryJSON(r *http.Request, dst interface{}) error

ParseQueryJSON parses the query values and the body of the request as JSON and stores the values in dst. If dst is a Validator, Validate is called and its error returned. The body is parsed as JSON regardless of the content-type of the request.

type Validator

type Validator interface {
	Validate() error
}

Validator defines the method required for a type to validate itself.

Jump to

Keyboard shortcuts

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