binding

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2022 License: MIT Imports: 17 Imported by: 1

README

binding

Bind request arguments easily in Golang.

test status

Usage

package main

import (
	"bytes"
	"fmt"
	"net/http"
	"time"

	"github.com/miclle/binding"
)

// MixStruct bind target struct
type MixStruct struct {
	Page       int        `query:"page"`
	PageSize   int        `query:"page_size"`
	IDs        []int      `query:"ids[]"`
	Start      *time.Time `query:"start"         time_format:"unix"`
	Referer    string     `header:"referer"`
	XRequestID string     `header:"X-Request-Id"`
	Vary       []string   `header:"vary"`
	Name       string     `json:"name"`
	Content    *string    `json:"content"`
}

func main() {

	var (
		obj        MixStruct
		url        = "/?page=1&page_size=30&ids[]=1&ids[]=2&ids[]=3&ids[]=4&ids[]=5&start=1669732749"
		referer    = "http://domain.name/posts"
		varyHeader = []string{"X-PJAX, X-PJAX-Container, Turbo-Visit, Turbo-Frame", "Accept-Encoding, Accept, X-Requested-With"}
		XRequestID = "l4dCIsjENo3QsCoX"
	)

	req, _ := http.NewRequest(http.MethodGet, url, nil)
	req.Header.Set("Referer", referer)
	req.Header.Set("X-Request-Id", XRequestID)
	req.Header.Add("vary", varyHeader[0])
	req.Header.Add("vary", varyHeader[1])

	_ = binding.Bind(req, &obj)

	fmt.Printf("%#v \n", obj)
	// MixStruct{
	//   Page:1,
	//   PageSize:30,
	//   IDs:[]int{1, 2, 3, 4, 5},
	//   Start:time.Date(2022, time.November, 29, 22, 39, 9, 0, time.Local),
	//   Referer:"http://domain.name/posts",
	//   XRequestID:"l4dCIsjENo3QsCoX",
	//   Vary:[]string{"X-PJAX, X-PJAX-Container, Turbo-Visit, Turbo-Frame", "Accept-Encoding, Accept, X-Requested-With"},
	//   Name:"",
	//   Content:(*string)(nil)
	// }

	req, _ = http.NewRequest(http.MethodPost, url, bytes.NewBufferString(`{"name": "Binder"}`))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Referer", referer)
	req.Header.Set("X-Request-Id", XRequestID)
	req.Header.Add("vary", varyHeader[0])
	req.Header.Add("vary", varyHeader[1])

	obj = MixStruct{}
	_ = binding.Bind(req, &obj)

	fmt.Printf("%#v \n", obj)
	// MixStruct{
	//   Page:1,
	//   PageSize:30,
	//   IDs:[]int{1, 2, 3, 4, 5},
	//   Start:time.Date(2022, time.November, 29, 22, 39, 9, 0, time.Local),
	//   Referer:"http://domain.name/posts",
	//   XRequestID:"l4dCIsjENo3QsCoX",
	//   Vary:[]string{"X-PJAX, X-PJAX-Container, Turbo-Visit, Turbo-Frame", "Accept-Encoding, Accept, X-Requested-With"},
	//   Name:"Binder",
	//   Content:(*string)(nil)
	// }
}

Documentation

Index

Constants

View Source
const (
	MIMEJSON              = "application/json"                  // json
	MIMEYAML              = "application/x-yaml"                // yaml
	MIMEXML               = "application/xml"                   // xml
	MIMEXML2              = "text/xml"                          // xml
	MIMEPOSTForm          = "application/x-www-form-urlencoded" // form
	MIMEMultipartPOSTForm = "multipart/form-data"               // form
	MIMEPROTOBUF          = "application/x-protobuf"            // protobuf
	MIMETOML              = "application/toml"                  // toml

	MIMEHTML  = "text/html"
	MIMEPlain = "text/plain"
)

Content-Type MIME of the most common data formats.

Variables

View Source
var (
	JSON          Binder    = jsonBinder{}
	XML           Binder    = xmlBinding{}
	YAML          Binder    = yamlBinding{}
	Form          Binder    = formBinder{}
	FormMultipart Binder    = formMultipartBinder{}
	ProtoBuf      Binder    = protobufBinding{}
	TOML          Binder    = tomlBinding{}
	Query         Binder    = queryBinding{}
	Header        Binder    = headerBinding{}
	URI           URIBinder = uriBinding{}
)

These implement the Binding interface and can be used to bind the data present in the request to struct instances.

View Source
var (

	// ErrConvertMapStringSlice can not convert to map[string][]string
	ErrConvertMapStringSlice = errors.New("can not convert to map slices of strings")

	// ErrConvertToMapString can not convert to map[string]string
	ErrConvertToMapString = errors.New("can not convert to map of strings")
)
View Source
var (
	// ErrMultiFileHeader multipart.FileHeader invalid
	ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader")

	// ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid
	ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader")
)
View Source
var EnableDecoderDisallowUnknownFields = false // TODO(m) migrate to binder global options

EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

View Source
var EnableDecoderUseNumber = false // TODO(m) migrate to binder global options

EnableDecoderUseNumber is used to call the UseNumber method on the JSON Decoder instance. UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.

View Source
var ErrBindNonPointerValue = errors.New("can not bind to non-pointer value")

ErrBindNonPointerValue is required bind pointer

Functions

func Bind

func Bind(req *http.Request, obj interface{}, params ...map[string][]string) error

Bind request arguments

Types

type Binder

type Binder interface {
	Bind(*http.Request, interface{}) error
}

Binder describes the interface which needs to be implemented for binding the data present in the request such as JSON request body, query parameters or the form POST.

type URIBinder

type URIBinder interface {
	BindURI(map[string][]string, interface{}) error
}

URIBinder adds BindURI method to Binding. BindUri is similar with Bind, but it reads the Params.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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