binding

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package binding 提供 HTTP 参数绑定功能。

Package binding 提供 HTTP 参数绑定功能。

该模块提供将 HTTP 请求数据(表单、查询参数、JSON 请求体)绑定到 Go 结构体的功能。 支持自定义结构体标签和字段验证。

功能特性

  • 表单数据绑定:将 POST 表单数据绑定到结构体
  • 查询参数绑定:将 URL 查询参数绑定到结构体
  • JSON 绑定:将 JSON 请求体解码到结构体
  • 自定义标签:支持自定义结构体标签名(默认 "form")
  • 字段验证:支持 required 标记的必填字段验证

使用方式

定义结构体:

type UserForm struct {
    Name  string `form:"name,required"`
    Email string `form:"email"`
    Age   int    `form:"age"`
}

绑定表单数据:

binder := binding.NewBinder()
var form UserForm
err := binder.Bind(req, &form)

绑定查询参数:

err := binder.BindQuery(req, &form)

绑定 JSON:

err := binder.BindJSON(req, &form)

使用自定义标签:

binder := binding.NewBinder(binding.WithTagName("json"))

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotPointer = &Error{Message: "target must be a pointer"}
	ErrNotStruct  = &Error{Message: "target must be a struct"}
)

哨兵错误。

Functions

This section is empty.

Types

type Binder

type Binder struct {
	// contains filtered or unexported fields
}

Binder 表单绑定器。

func NewBinder

func NewBinder(opts ...Option) *Binder

NewBinder 创建一个新的表单绑定器。

func (*Binder) Bind

func (b *Binder) Bind(req *http.Request, target any) error

Bind 将 HTTP 请求表单数据绑定到结构体。

func (*Binder) BindJSON

func (b *Binder) BindJSON(req *http.Request, target any) error

BindJSON 将 JSON 请求体绑定到结构体。

func (*Binder) BindQuery

func (b *Binder) BindQuery(req *http.Request, target any) error

BindQuery 将 HTTP 请求查询参数绑定到结构体。

type Error

type Error struct {
	Field   string
	Message string
}

Error 表示绑定错误。

func (*Error) Error

func (e *Error) Error() string

Error 返回绑定错误的描述信息。

type Option

type Option func(*Binder)

Option 配置绑定器。

func WithTagName

func WithTagName(tagName string) Option

WithTagName 设置结构体标签名称(默认: "form")。

Jump to

Keyboard shortcuts

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