binding

package
v0.0.0-...-85b7a69 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2018 License: MIT Imports: 11 Imported by: 0

README

基于gin binding的自动绑定库

在原来基础上做了如下修改

  1. 将原来的校验库从http://gopkg.in/go-playground/validator.v8替换成http://gopkg.in/go-playground/validator.v9
  2. 增加gin PATH变量的binding
  3. 将所有binding的字段都统一到tag的json标签,去除之前的form标签依赖
  4. 增加可选变量绑定到指针的支持(若不存在,指针为空)
  5. Validate函数暴露出来,用于只需要校验的场景

校验规则,请参考 http://godoc.org/gopkg.in/go-playground/validator.v9

使用前,运行命令 ./dep.sh 来下载工具 govendor 以及使用govendor同步所有依赖的库

用法

func Test(c *gin.Context) {
    var form CreateMenuParam
    err, _ := binding.Bind(c, form);
}

若无法自动判定使用的bind后端(form/json等),可以使用

// BindJSON is a shortcut for c.BindWith(obj, binding.JSON)
func BindJSON(c * gin.Context,obj interface{}) (error,[]string) {
	return BindWith(c, obj, JSON)
}

// BindWith binds the passed struct pointer using the specified binding engine.
// See the binding package.
func BindWith(c * gin.Context,obj interface{}, b Binding) (error,[]string) {
	err := b.Bind(c, obj)
	return parseError(err,obj)
}

若已经完成了绑定,只需要校验,可以使用

func Validate(obj interface{}) error {
	if Validator == nil {
		return nil
	}
	return Validator.ValidateStruct(obj)
}

Documentation

Index

Constants

View Source
const (
	MIMEJSON              = "application/json"
	MIMEHTML              = "text/html"
	MIMEXML               = "application/xml"
	MIMEXML2              = "text/xml"
	MIMEPlain             = "text/plain"
	MIMEPOSTForm          = "application/x-www-form-urlencoded"
	MIMEMultipartPOSTForm = "multipart/form-data"
)

Variables

View Source
var (
	JSON          = jsonBinding{}
	XML           = xmlBinding{}
	Form          = formBinding{}
	FormPost      = formPostBinding{}
	FormMultipart = formMultipartBinding{}
)

Functions

func SetWithProperType

func SetWithProperType(valueKind reflect.Type, val string, structField reflect.Value) error

func Validate

func Validate(obj interface{}) error

Types

type Binding

type Binding interface {
	Name() string
	Bind(*http.Request, interface{}) error
}

func Default

func Default(method, contentType string) Binding

type StructValidator

type StructValidator interface {
	// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
	// If the received type is not a struct, any validation should be skipped and nil must be returned.
	// If the received type is a struct or pointer to a struct, the validation should be performed.
	// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
	// Otherwise nil must be returned.
	ValidateStruct(interface{}) error
}
var Validator StructValidator = &defaultValidator{}

Jump to

Keyboard shortcuts

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