shape README

The project's README from github.com/rhevorn/shape. As one markdown file: 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)

Searching Database…

What is this?Shape is a type-safe, dependency-free schema validation library for Go that lets you describe a struct once and reuse it to transform, validate, and parse JSON into Go values.
Is it a framework or a library?It is a Go library made of composable packages (validate, transform, jsonschema, openapi) with a generics-based public API, not a framework or standalone app.
How do I add it to a project?Install it as a Go module (requires Go 1.24+), then define a schema with shape.NewT or struct tags and call Transform, Validate, ValidateFirst, or ParseJSON/BindJSON on it.
Do I need any external dependencies to run it?No, the runtime packages rely only on the Go standard library, so there are no third-party dependencies to install.
Any install pitfalls or gotchas with schemas?Invalid field names and incompatible field types are caught when a schema is created, and the optional shapevet static analyzer is needed for extra tag/schema checks at compile time; without it, bad definitions are only caught at runtime.
Does validation stop at the first error or collect all of them?You can choose: Validate collects every issue found, while ValidateFirst stops as soon as the first issue is hit.
Can I generate JSON Schema or OpenAPI definitions from a shape schema?Yes, the jsonschema package produces JSON Schema Draft 2020-12 output and the openapi package produces OpenAPI 3.1 adapters from the same schema definitions.
Are validation error messages only in English?No, built-in error messages support multiple locales out of the box, including English and Simplified Chinese, and you can attach a locale via context.
What is shapevet?shapevet is an optional static analyzer that checks fluent method names, struct tags, and explicit schema field names at compile time; without it, invalid schema definitions are still caught at runtime instead.
Creator
rhevorn
Size
0.8 MB
Stars
170
Updated
CommitSep 20
Age
2mo
Commits · 90 Days