bind

package module
v0.0.0-...-05b1f89 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2023 License: Apache-2.0 Imports: 9 Imported by: 20

README

Go Reference

ugent-library/bind

Package bind contains convenience functions to decode HTTP request data.

It can bind header values, router path variables, query parameters, form data and a json or xml body to a struct.

The package uses go-playground/form under the hood for header, form and query decoding.

Install

go get -u github.com/ugent-library/bind

Examples

    type UserForm struct {
        ID        int    `path:"user_id"`
        FirstName string `form:"first_name" query:"first_name" json:"first_name"`
        LastName  string `form:"last_name" query:"last_name" json:"last_name"`
    }

    // if the struct implements bind.Validator, ValidateBind() will be called
    // after a successful bind.Request()
    func (f *UserForm) ValidateBind() error {
        if f.LastName == "" {
            return errors.New("validation failed: last name can't be empty")
        }        
    }

    http.HandleFunc("/echo/user", func(w http.ResponseWriter, r *http.Request) {
        u := UserForm{}
        if err := bind.Request(r, &u); err != nil {
            // handle error
        }
        fmt.Fprintf(w, "%d: %s %s", u.ID, u.FirstName, u.LastName)
    })

Documentation

Overview

Package bind contains convenience functions to decode HTTP request data.

Index

Constants

This section is empty.

Variables

View Source
var (
	PathValueFunc func(*http.Request, string) string
)

Functions

func Body

func Body(r *http.Request, v any, flags ...Flag) error

func DecodeForm

func DecodeForm(vals url.Values, v any, flags ...Flag) error

func DecodeHeader

func DecodeHeader(header http.Header, v any, flags ...Flag) error

func DecodeQuery

func DecodeQuery(vals url.Values, v any, flags ...Flag) error

func EncodeForm

func EncodeForm(v any) (url.Values, error)

func EncodeHeader

func EncodeHeader(v any) (http.Header, error)

func EncodeQuery

func EncodeQuery(v any) (url.Values, error)
func Header(r *http.Request, v any, flags ...Flag) error

func Path

func Path(r *http.Request, v any, flags ...Flag) error

func PathValue

func PathValue(r *http.Request, k string) string

func Query

func Query(r *http.Request, v any, flags ...Flag) error

func Request

func Request(r *http.Request, v any, flags ...Flag) error

Types

type Flag

type Flag int
const (
	// When the Vacuum flag is set, url.Values is cleaned before trying to bind the values.
	// Strings are trimmed, empty strings and zero length slices are deleted.
	Vacuum Flag = iota
)

type Validator

type Validator interface {
	ValidateBind() error
}

Jump to

Keyboard shortcuts

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