param

package
v2.0.0-alpha.95 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ByteLengthAtLeast

func ByteLengthAtLeast[T string](min int) *checker[T]

func ByteLengthAtMost

func ByteLengthAtMost[T string](max int) *checker[T]

func ByteLengthBetween

func ByteLengthBetween[T string](min, max int) *checker[T]

func CharLengthAtLeast

func CharLengthAtLeast[T string](min int) *checker[T]

func CharLengthAtMost

func CharLengthAtMost[T string](max int) *checker[T]

func CharLengthBetween

func CharLengthBetween[T string](min, max int) *checker[T]

func New

func New[T internal.ParamTypes](key string) *param[T]

Create a parameter.

func NewChecker

func NewChecker[T internal.ParamTypes](f CheckerFunc[T]) *checker[T]

Creates a checker. Checkers are used by the Param object via param.WithCheckers method. A checker must have a handler function with the following signature:

func(T) (*any, string, []any)

The input parameter of this function is the value to be checked. In its output, the first value is a pointer to the checked value, the second value is the error message, and the third value is the variables in the error message (i.e., how fmt.Sprintf is used). The framework determines parameter compliance based on whether the second parameter is empty after calling the checking function. If the check is successful, it checks if the first parameter is nil; if it is not nil, the value pointed to by that pointer is used to replace the parameter's value. For example,

param.New[uint32]("uid").WithCheckers(
	param.NewChecker[uint32](func(id uint32) (*any, string, []any) {
	    row := db.QueryRow(`SELECT * FROM users WHERE id=?`, id)
		u, err := rowToUser(row)
		if err != nil {
			return nil, err.Error(), nil
		}
		v := any(u)
		return &v, "", nil
	}).WithHelp("User ID must exist in the database")

In this example, there are a few points to note:

  • Although `uid` is defined as an integer type, the final output parameter value is a `user` object. In other words, by using a checker, HTTP parameters can be converted to any required type. In the Action function, if a parameter has not been type-converted, it is used as follows:

    uid := arg.Get[uint64](a, "uid")

    If it is converted to a `User` object in the above example, it would be:

    user := a.Value("uid").(*User)

  • Generally, a checker function only checks the format and range of a parameter. Performing database queries in a checker function is not always a good practice due to its lack of generality. This logic is better handled in the Action function compared to the checker. If it is necessary to perform in-depth preprocessing of parameters in the checker, consider using some caching mechanisms to improve performance.

This package provides several ready-to-use checkers, as demonstrated in the following example:

handler.GET().WithParams(
    param.New[string]("ident").WithCheckers(
	    param.LengthBetween[string](1, 16),
	    param.TextConsistsOf[string](param.AlphaNumeric),
	).WithHelp("resource identity"),
	param.New[uint16]("amount").WithCheckers(
	    param.ValueLessThan[uint16](1000),
	),
	param.New[string]("payment").WithCheckers(
	    param.ValueIsOneOf[string]("master", "visa").
		    WithHelp("only 'master' or 'visa' are supported"),
	)
).WithAction(apiGet)

This example illustrates:

  • How to define parameters for a handler.
  • That a parameter can have multiple checkers.
  • That each checker can include a custom help message. If a custom message is not provided, a default help message is used, with support for localization.

For a complete list of predefined checkers, refer to this document page. All these checkers are designed to be self-explanatory and intuitive.

func TextConsistsOf

func TextConsistsOf[T string](chars Charset) *checker[T]

func TextHasPrefix

func TextHasPrefix[T string](pfx string, caseFold bool) *checker[T]

func TextHasSuffix

func TextHasSuffix[T string](sfx string, caseFold bool) *checker[T]

func TextIsOneOf

func TextIsOneOf[T string](vs ...string) *checker[T]

Similar to ValueIsOneOf, but the comparison is case-insensitive for the `vs` values.

func TextMatches

func TextMatches[T string](expr string) *checker[T]

Text must match regular expression `expr`. There is an "extension" to the standard Go regular expression syntax: `(?v)pattern`, which means do NOT match the given pattern.

func ValueBetween

func ValueBetween[T internal.Numbers](min, max T) *checker[T]

func ValueGreaterThan

func ValueGreaterThan[T internal.Numbers](min T) *checker[T]

func ValueIsOneOf

func ValueIsOneOf[T internal.ParamTypes](vs ...T) *checker[T]

func ValueLessThan

func ValueLessThan[T internal.Numbers](max T) *checker[T]

Types

type Charset

type Charset string

Represents a set of characters used for validation purposes in a Checker.

const (
	UpperCase    Charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	LowerCase    Charset = "abcdefghijklmnopqrstuvwxyz"
	Alphabetic   Charset = UpperCase + LowerCase
	Numeric      Charset = "0123456789"
	AlphaNumeric Charset = Alphabetic + Numeric
	Decimal      Charset = Numeric
	Hexadecimal  Charset = Decimal + "abcdefABCDEF"
)

type CheckerFunc

type CheckerFunc[T internal.ParamTypes] func(T) (*any, string, []any)

type Param

type Param interface {
	//Returns the default value of the parameter, if any.
	Default() *string
	//Provides localizable help text for the parameter.
	Help(*message.Printer) []string
	//Returns the name of the parameter.
	Name() string
	//Parses URL values into arguments according to parameter spec.
	Parse(url.Values) ([]any, []internal.ParametricMessage)
	//Indicates whether the parameter is required.
	Required() bool
	//Defines the validation rules for the parameter.
	Rules(*message.Printer) [][]string
	//Returns the type of the parameter.
	Type() string
}

Represents the specification of an HTTP parameter

Jump to

Keyboard shortcuts

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