param

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2022 License: MIT Imports: 7 Imported by: 0

README

Param GoDoc

param deserializes parameter values into a given struct using magical reflection ponies.

Inspired by gorilla/schema, but uses Rails/jQuery style param encoding instead of their weird dotted syntax. In particular, this package was written with the intent of parsing the output of jQuery.param.

This package uses struct tags to guess what names things ought to have. If a struct value has a "param" tag defined, it will use that. If there is no "param" tag defined, the name part of the "json" tag will be used. If that is not defined, the name of the field itself will be used (no case transformation is performed).

If the name derived in this way is the string "-", param will refuse to set that value.

The parser is extremely strict, and will return an error if it has any difficulty whatsoever in parsing any parameter, or if there is any kind of type mismatch.

Example

Here's how to use param to parse the contents of a web form:


import (
    "net/http"
    "github.com/goji/param"
)

type SignupForm struct {
    Name string `param:"name"`
    Email string `param:"email_address"`
    // We use a struct tag with "-" to ignore a value.
    Password string `param:"-"`
}

// FormHandler accepts a POST request, and would typically handle a HTML 
// form with a format like this:
// 
//  <form action="/signup/submit" method="POST">
//  <input name="name" type="text">
//  <input name="email_address" type="text">
//  <input name="password" type="password">
//  <input type="submit" value="Signup!">
//  </form>
//
// The 'name' attributes should match up with those of our struct fields. If 
// they don't, we use the aforementioned struct tags to translate them.
func FormHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        http.Error(w, "No good!", 400)
        return
    }

    var signupForm SignupForm{}
    // Parse url.Values (in this case, r.PostForm) and 
    // a pointer to our struct so that param can populate it.
    err := param.Parse(r.PostForm, &signupForm)
    if err != nil {
        http.Error(w, "Real bad.", 500)
        return
    }

    // Now we can:
    // - Perform some validation on our values
    // - Hash the user password with bcrypt or scrypt
    // - Store the results in our database
    // - (the world is our oyster!)
}

It's pretty simple! Note that you can also inspect the errors returned from param.Parse if you wish. Error types are documented over on GoDoc.

License

MIT licensed. See the LICENSE file for details.

Documentation

Overview

Package param deserializes parameter values into a given struct using magical reflection ponies. Inspired by gorilla/schema, but uses Rails/jQuery style param encoding instead of their weird dotted syntax. In particular, this package was written with the intent of parsing the output of jQuery.param.

This package uses struct tags to guess what names things ought to have. If a struct value has a "param" tag defined, it will use that. If there is no "param" tag defined, the name part of the "json" tag will be used. If that is not defined, the name of the field itself will be used (no case transformation is performed).

If the name derived in this way is the string "-", param will refuse to set that value.

The parser is extremely strict, and will return an error if it has any difficulty whatsoever in parsing any parameter, or if there is any kind of type mismatch.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

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

Parse the given arguments into the the given pointer to a struct object.

Types

type InvalidParseError

type InvalidParseError struct {
	Type reflect.Type
	Hint string
}

InvalidParseError describes an invalid argument passed to Parse. It is always the result of programmer error.

func (InvalidParseError) Error

func (err InvalidParseError) Error() string

type KeyError

type KeyError struct {
	// The full key that was in error.
	FullKey string
	// The key of the struct that did not have the given field.
	Key string
	// The type of the struct that did not have the given field.
	Type reflect.Type
	// The name of the field which was not present.
	Field string
}

KeyError is an error type returned when an unknown field is set on a struct.

func (KeyError) Error

func (k KeyError) Error() string

type NestingError

type NestingError struct {
	// The portion of the key that was correctly parsed into a value.
	Key string
	// The type of the key that was invalidly nested on.
	Type reflect.Type
	// The portion of the key that could not be parsed due to invalid
	// nesting.
	Nesting string
}

NestingError is an error type returned when a key is nested when the target type does not support nesting of the given type. For example, deserializing the parameter key "anint[foo]" into a struct that defines an integer param "anint" will produce a NestingError with key "anint" and nesting "[foo]".

func (NestingError) Error

func (n NestingError) Error() string

type SingletonError

type SingletonError struct {
	// The key that was in error.
	Key string
	// The type that was expected for that key.
	Type reflect.Type
	// The list of values that were provided for that key.
	Values []string
}

SingletonError is an error type returned when a parameter is passed multiple times when only a single value is expected. For example, for a struct with integer field "foo", "foo=1&foo=2" will return a SingletonError with key "foo".

func (SingletonError) Error

func (s SingletonError) Error() string

type SyntaxError

type SyntaxError struct {
	// The key for which there was a syntax error.
	Key string
	// The subtype of the syntax error, which describes what sort of error
	// was encountered.
	Subtype SyntaxErrorSubtype
	// The part of the key (generally the suffix) that was in error.
	ErrorPart string
}

SyntaxError is an error type returned when a key is incorrectly formatted.

func (SyntaxError) Error

func (s SyntaxError) Error() string

type SyntaxErrorSubtype

type SyntaxErrorSubtype int

SyntaxErrorSubtype describes what sort of syntax error was encountered.

const (
	MissingOpeningBracket SyntaxErrorSubtype = iota + 1
	MissingClosingBracket
)

type ValueError

type ValueError struct {
	// The key that was in error.
	Key string
	// The type that was expected.
	Type reflect.Type
	// The underlying error produced as part of the deserialization process,
	// if one exists.
	Err error
}

ValueError is an error type returned when param has difficulty deserializing a parameter value.

func (ValueError) Error

func (v ValueError) Error() string

Notes

Bugs

  • We currently do not handle slices of nested types. If support is needed, the implementation probably could be fleshed out.

  • We don't support any map keys except strings, although there's no reason we shouldn't be able to throw the value through our unparsing stack.

Jump to

Keyboard shortcuts

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