queryparam

package module
v4.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2019 License: MIT Imports: 7 Imported by: 0

README

Query Param

Build Status codecov Go Report Card Documentation

Stop accessing query strings and parsing repeatedly parsing them into your preferred values - queryparam can do that for you!

Installation

go get -u github.com/tomwright/queryparam

Examples

For examples see godoc examples.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNonPointerTarget is returned when the given interface does not represent a pointer
	ErrNonPointerTarget = errors.New("invalid target. must be a non nil pointer")
	// ErrInvalidURLValues is returned when the given *url.URL is nil
	ErrInvalidURLValues = errors.New("invalid url provided")
	// ErrUnhandledFieldType is returned when a struct property is tagged but has an unhandled type.
	ErrUnhandledFieldType = errors.New("unhandled field type")
	// ErrInvalidTag is returned when the tag value is invalid
	ErrInvalidTag = errors.New("invalid tag")
)
View Source
var DefaultParser = &Parser{
	Tag:          "queryparam",
	DelimiterTag: "queryparamdelim",
	Delimiter:    ",",
	ValueParsers: DefaultValueParsers(),
	ValueSetters: DefaultValueSetters(),
}

DefaultParser is a default parser.

View Source
var ErrInvalidBoolValue = errors.New("unknown bool value")

ErrInvalidBoolValue is returned when an unhandled string is parsed.

View Source
var GenericType = reflect.TypeOf(struct{}{})

GenericType is a reflect.Type we can use to identity generic value setters.

Functions

func BoolValueParser

func BoolValueParser(value string, _ string) (reflect.Value, error)

BoolValueParser parses a string into a bool.

func DefaultValueParsers

func DefaultValueParsers() map[reflect.Type]ValueParser

DefaultValueParsers returns a set of default value parsers.

func DefaultValueSetters

func DefaultValueSetters() map[reflect.Type]ValueSetter

DefaultValueSetters returns a set of default value setters.

func Float32ValueParser

func Float32ValueParser(value string, _ string) (reflect.Value, error)

Float32ValueParser parses a string to a float32.

func Float32ValueSetter

func Float32ValueSetter(value reflect.Value, target reflect.Value) (err error)

Float32ValueSetter sets the targets value to a float32.

func Float64ValueParser

func Float64ValueParser(value string, _ string) (reflect.Value, error)

Float64ValueParser parses a string to a float64.

func GenericSetter

func GenericSetter(value reflect.Value, target reflect.Value) (err error)

GenericSetter sets the targets value.

func Int32ValueParser

func Int32ValueParser(value string, _ string) (reflect.Value, error)

Int32ValueParser parses a string into an int32.

func Int32ValueSetter

func Int32ValueSetter(value reflect.Value, target reflect.Value) (err error)

Int32ValueSetter sets the targets value to an int32.

func Int64ValueParser

func Int64ValueParser(value string, _ string) (reflect.Value, error)

Int64ValueParser parses a string into an int64.

func IntValueParser

func IntValueParser(value string, _ string) (reflect.Value, error)

IntValueParser parses a string into an int64.

func Parse

func Parse(urlValues url.Values, target interface{}) error

Parse attempts to parse query parameters from the specified URL and store any found values into the given target interface.

Example

ExampleParse creates a dummy http request and parses the data into a struct

urlValues := url.Values{}
urlValues.Set("name", "Tom")
urlValues.Set("names", "Tom,Jim,Frank")      // list of names separated by ,
urlValues.Set("dash-names", "Tom-Jim-Frank") // list of names separated by -
urlValues.Set("age", "123")
urlValues.Set("age32", "123")
urlValues.Set("age64", "123")
urlValues.Set("float32", "123.45")
urlValues.Set("float64", "123.45")
urlValues.Set("created-at", "2019-02-05T13:32:02Z")
urlValues.Set("bool-false", "false")
urlValues.Set("bool-true", "true")
urlValues.Set("bool-empty", "")    // param set but no value means
urlValues.Set("present-empty", "") // param set but no value
urlValues.Set("present", "this is here")

requestData := struct {
	Name         string             `queryparam:"name"`
	Names        []string           `queryparam:"names"`
	DashNames    []string           `queryparam:"dash-names" queryparamdelim:"-"`
	Age          int                `queryparam:"age"`
	Age32        int32              `queryparam:"age32"`
	Age64        int64              `queryparam:"age64"`
	Float32      float32            `queryparam:"float32"`
	Float64      float64            `queryparam:"float64"`
	CreatedAt    time.Time          `queryparam:"created-at"`
	UpdatedAt    time.Time          `queryparam:"updated-at"`
	BoolFalse    bool               `queryparam:"bool-false"`
	BoolTrue     bool               `queryparam:"bool-true"`
	BoolEmpty    bool               `queryparam:"bool-empty"`
	PresentEmpty queryparam.Present `queryparam:"present-empty"`
	Present      queryparam.Present `queryparam:"present"`
	NotPresent   queryparam.Present `queryparam:"not-present"`
}{}

if err := queryparam.Parse(urlValues, &requestData); err != nil {
	panic(err)
}

fmt.Printf("name: %s\n", requestData.Name)
fmt.Printf("names: %v\n", requestData.Names)
fmt.Printf("dash names: %v\n", requestData.DashNames)
fmt.Printf("age: %d\n", requestData.Age)
fmt.Printf("age32: %d\n", requestData.Age32)
fmt.Printf("age64: %d\n", requestData.Age64)
fmt.Printf("float32: %f\n", math.Round(float64(requestData.Float32))) // rounded to avoid floating point precision issues
fmt.Printf("float64: %f\n", math.Round(requestData.Float64))          // rounded to avoid floating point precision issues
fmt.Printf("created at: %s\n", requestData.CreatedAt.Format(time.RFC3339))
fmt.Printf("updated at: %s\n", requestData.UpdatedAt.Format(time.RFC3339))
fmt.Printf("bool false: %v\n", requestData.BoolFalse)
fmt.Printf("bool true: %v\n", requestData.BoolTrue)
fmt.Printf("bool empty: %v\n", requestData.BoolEmpty)
fmt.Printf("present empty: %v\n", requestData.PresentEmpty)
fmt.Printf("present: %v\n", requestData.Present)
fmt.Printf("not present: %v\n", requestData.NotPresent)
Output:

name: Tom
names: [Tom Jim Frank]
dash names: [Tom Jim Frank]
age: 123
age32: 123
age64: 123
float32: 123.000000
float64: 123.000000
created at: 2019-02-05T13:32:02Z
updated at: 0001-01-01T00:00:00Z
bool false: false
bool true: true
bool empty: false
present empty: false
present: true
not present: false

func PresentValueParser

func PresentValueParser(value string, _ string) (reflect.Value, error)

PresentValueParser sets the target to true. This parser will only be executed if the parameter is present.

func StringSliceValueParser

func StringSliceValueParser(value string, delimiter string) (reflect.Value, error)

StringSliceValueParser parses a string into a []string.

func StringValueParser

func StringValueParser(value string, _ string) (reflect.Value, error)

StringValueParser parses a string into a string.

func TimeValueParser

func TimeValueParser(value string, _ string) (reflect.Value, error)

TimeValueParser parses a string into an int64.

Types

type ErrCannotSetValue

type ErrCannotSetValue struct {
	Err         error
	Parameter   string
	Field       string
	Value       string
	Type        reflect.Type
	ParsedValue reflect.Value
}

ErrCannotSetValue is an error adds extra context to a setter error.

func (*ErrCannotSetValue) Error

func (e *ErrCannotSetValue) Error() string

Error returns the full error message.

func (*ErrCannotSetValue) Unwrap

func (e *ErrCannotSetValue) Unwrap() error

Unwrap returns the wrapped error.

type ErrInvalidParameterValue

type ErrInvalidParameterValue struct {
	Err       error
	Parameter string
	Field     string
	Value     string
	Type      reflect.Type
}

ErrInvalidParameterValue is an error adds extra context to a parser error.

func (*ErrInvalidParameterValue) Error

func (e *ErrInvalidParameterValue) Error() string

Error returns the full error message.

func (*ErrInvalidParameterValue) Unwrap

func (e *ErrInvalidParameterValue) Unwrap() error

Unwrap returns the wrapped error.

type Parser

type Parser struct {
	// Tag is the name of the struct tag where the query parameter name is set.
	Tag string
	// Delimiter is the name of the struct tag where a string delimiter override is set.
	DelimiterTag string
	// Delimiter is the default string delimiter.
	Delimiter string
	// ValueParsers is a map[reflect.Type]ValueParser that defines how we parse query
	// parameters based on the destination variable type.
	ValueParsers map[reflect.Type]ValueParser
	// ValueSetters is a map[reflect.Type]ValueSetter that defines how we set values
	// onto target variables.
	ValueSetters map[reflect.Type]ValueSetter
}

Parser is used to parse a URL.

func (*Parser) FieldDelimiter

func (p *Parser) FieldDelimiter(field reflect.StructField) string

FieldDelimiter returns a delimiter to be used with the given field.

func (*Parser) Parse

func (p *Parser) Parse(urlValues url.Values, target interface{}) error

Parse attempts to parse query parameters from the specified URL and store any found values into the given target interface.

func (*Parser) ParseField

func (p *Parser) ParseField(field reflect.StructField, value reflect.Value, urlValues url.Values) error

ParseField parses the given field and sets the given value on the target.

type Present

type Present bool

Present allows you to determine whether or not a query parameter was present in a request.

type ValueParser

type ValueParser func(value string, delimiter string) (reflect.Value, error)

ValueParser is a func used to parse a value.

type ValueSetter

type ValueSetter func(value reflect.Value, target reflect.Value) error

ValueSetter is a func used to set a value on a target variable.

Jump to

Keyboard shortcuts

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