shape README

项目的 README,来自 github.com/rhevorn/shape。合并为一个 markdown 文件:README.md。

shape

CI Go Reference Go Report Card License: MIT

Typed validation, transformation, and JSON, form, and query binding for Go.

Describe a struct once, then transform, validate, or parse input with the same definition. Invalid field configuration panics; bad input returns errors.

Features

Status

Preparing the first public release. The public surface and behavioral contract are specified in docs/API.md; after the first public tag, incompatible changes require a major version.

Install

go get github.com/rhevorn/shape

Requires Go 1.24 or newer.

Struct tags

For simple DTOs, put rules on the struct and bind with no Schema variable:

type CreateUserRequest struct {
	Name string `json:"name" form:"name" query:"name" shape:"trim,notempty,maxlength=50"`
	Age  int    `json:"age" form:"age" query:"age" shape:"min=18,max=120"`
}

var request CreateUserRequest
err := shape.BindJSON(&request, data)

BindJSON writes the target only after the full pipeline succeeds. Use shape.FromTags[CreateUserRequest]() to reuse the tagged Schema explicitly.

Explicit Schema

Field behavior written in Go with shape.New:

type User struct {
	Name string   `json:"name" form:"name" query:"name"`
	Age  int      `json:"age" form:"age" query:"age"`
	Tags []string `json:"tags" form:"tags" query:"tags"`
}

var userSchema = shape.New[User](
	shape.Field("Name", shape.String().Trim().NotEmpty().MaxLength(50)),
	shape.Field("Age", shape.Int().Min(18).Max(120)),
	shape.Field("Tags", shape.Slice(shape.String().Trim().NotEmpty()).NotEmpty().Unique()),
)

data := []byte(`{
	"name": " Pong ",
	"age": 20,
	"tags": [" go ", "shape"]
}`)

user, err := userSchema.ParseJSON(data)
// user.Name == "Pong"

The equivalent package-level call is:

user, err := shape.ParseJSON(userSchema, data)

Both forms decode, transform, and validate in one call. Schemas created with shape.New[T] or shape.FromTags[T] support the method form; the package function accepts any Schema[T], including scalars and collections.

Field names and their target types are checked at construction; generics check value and collection composition. Optional shapevet catches statically visible binding mistakes before runtime.

The same schema also supports Transform and Validate on typed values. Value factories such as String, Slice, and Map never take a field name; Field is the single explicit bridge from a value Schema to a struct field.

Forms and query parameters

The same struct Schema accepts url.Values:

values := url.Values{
    "name": {" Pong "},
    "age":  {"20"},
    "tags": {"go", "shape"},
}

// Schema methods.
user, err := userSchema.ParseForm(values)
user, err = userSchema.ParseQuery(values)

// Equivalent package functions.
user, err = shape.ParseForm(userSchema, values)
user, err = shape.ParseQuery(userSchema, values)

For tagged DTOs, use shape.BindForm(&request, values) or shape.BindQuery(&request, values). All calls have context variants and Bind updates its target only on success.

Each input uses its own tag (json, form, or query), falling back to the Go field name. Input tags never change the Schema’s transformation or validation rules. Repeated parameters bind to slices; repeated scalars return an error. Nested structs use names such as address.city.

For HTTP forms, parse the request and pass r.PostForm or r.MultipartForm.Value. For queries, use url.ParseQuery(r.URL.RawQuery) and check its error before passing the values. See Forms and query parameters for decoding rules, strict options, and HTTP examples.

HTTP requests

For automatic Query and body binding:

var request CreateUserRequest
err := shape.BindRequest(&request, r, shape.RequestOptions{
    DisallowUnknownFields: true,
})

Query uses query tags. Content-Type selects JSON (json tags) or Form (form tags) for the body. A field submitted by both sources returns a conflict error; set Precedence: shape.QueryFirst or shape.BodyFirst for explicit precedence. Objects and slices are replaced as whole top-level fields, never recursively merged. The combined value is transformed and validated once before replacing the target. The default body limit is 1 MiB; multipart file parts require manual handling. See HTTP binding.

Scalars

Standalone string Specs work the same way without a struct:

name := shape.String().Trim().ToLower().NotEmpty()

out, err := name.Transform(" Pong ")
// out == "pong", err == nil

err = name.Validate(out)

Documentation

License

MIT

shape (rhevorn/shape)

正在搜索数据库…

这是什么?Shape 是一个类型安全、零依赖的 Go schema 校验库,让你只需描述一次 struct,就能复用它来进行转换、校验,以及把 JSON 解析为 Go 值。
它是框架还是库?它是一个由可组合的包(validate、transform、jsonschema、openapi)构成的 Go 库,公共 API 基于泛型,不是框架也不是独立应用。
怎么把它加到项目里?把它作为 Go 模块安装(需要 Go 1.24+),然后用 shape.NewT 或 struct 标签定义 schema,并在其上调用 Transform、Validate、ValidateFirst 或 ParseJSON/BindJSON。
运行它需要任何外部依赖吗?不需要,运行时包只依赖 Go 标准库,无需安装任何第三方依赖。
安装或 schema 方面有什么坑吗?无效的字段名和不兼容的字段类型在创建 schema 时就会被捕获;如果想在编译期做额外的标签/schema 检查,需要可选的 shapevet 静态分析器;没有它的话,错误的定义只能在运行时被发现。
校验是在第一个错误时就停止,还是收集所有错误?可以自选:Validate 会收集发现的每个问题,而 ValidateFirst 在遇到第一个问题时立即停止。
能从 shape schema 生成 JSON Schema 或 OpenAPI 定义吗?可以,jsonschema 包能从同一套 schema 定义生成 JSON Schema Draft 2020-12 输出,openapi 包则生成 OpenAPI 3.1 适配器。
校验错误信息只有英文吗?不是,内置错误信息开箱即支持多种语言,包括英文和简体中文,你可以通过 context 附加区域设置。
shapevet 是什么?shapevet 是一个可选的静态分析器,在编译期检查链式方法名、struct 标签和显式指定的 schema 字段名;没有它,无效的 schema 定义仍会在运行时被捕获。
作者
rhevorn
大小
0.8 MB
星标
170
更新
提交Sep 20
时长
2个月
提交 · 90 天