c3po

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2025 License: BSD-3-Clause Imports: 9 Imported by: 1

README

C3PO

GoLang data validator – simples, flexível e extensível.

C3PO é um validador de dados rápido e minimalista para Go.
Ele é pensado para ser leve, intuitivo e fácil de extender — sem refletividade pesada ou configurações complexas.

Features ✨

  • 🔥 Validação por tags (required, min, max,minlen)
  • ⚡ Sem mágica: fácil de entender e debuggar
  • 🛠️ Extensível: adicione suas próprias validações
  • 🏎️ Alto desempenho: ideal para aplicações críticas

Instalação

go get 5tk.dev/c3po

Exemplo rápido

package main

import (
    "fmt"
    "5tk.dev/c3po"
)

type User struct {
    Name string `validate:"required"`
    Age  int    `validate:"min=18"`
}

func main() {
    user := &User{}
    sch := c3po.Validate(user,map[string]any{"name": "cleitu", "age": "15"})
    if sch.HasErrors() {
        panic(sch.Errors())
    }
    u := sch.Value().(*User)
    fmt.Println(u) 
}

Validações suportadas

Tag Descrição
required Campo obrigatório
min Valor mínimo (número)
max Valor máximo (número)
minlen Valor máximo (tamanho)
maxlen Valor máximo (tamanho)
escape Html Escape

Extensões e validações customizadas

Crie novas tags facilmente:

c3po.SetRule("now", func(field reflect.Value, param string) error {
    field.Set(reflect.ValueOf(time.Now()))
    return nil
})

type Foo struct{
    CreatedAt time.Time `c3po:"now"`
}

Roadmap 🚀

  • Sistema de validação básico (required, min, max)
  • Middleware de validação para http.Request
  • Diretório de exemplos
  • Documentação completa
  • Benchmarks

Contribuindo

Pull requests são bem-vindos!
Se encontrar algum bug ou tiver ideias de melhoria, abra uma issue.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetFunctionName

func GetFunctionName(i interface{}) string

func HtmlEscape

func HtmlEscape(s string) string

func IsValidationError

func IsValidationError(err error) bool

func RegisterFielder

func RegisterFielder(key string, schema *Fielder) error

func RetInvalidType

func RetInvalidType(f *Fielder) error

func RetInvalidValue

func RetInvalidValue(f *Fielder) error

func RetMissing

func RetMissing(f *Fielder) error

func SetReflectValue

func SetReflectValue(rcv reflect.Value, v reflect.Value) bool

try convert and set a value of v in rcv

func SetRule

func SetRule(field string, rule *Rule)

ex:

	c3po.SetRules("min",&c3po.Rule{Message:"min value: {value}"}) // '{value}' be replace by "Rule.Value"
	c3po.SetRules("max",&c3po.Rule{Message:"max value: {value}"}) // '{value}' be replace by "Rule.Value"
	c3po.SetRules("format",&c3po.Rule{Validate:func(value any) bool {...}})

	type User struct {
		Age int `c3po:"min=18"`
 }

func UnmarshalValidate

func UnmarshalValidate(dst, src any) error

Types

type Fielder

type Fielder struct {
	Name     string
	Type     reflect.Kind
	Tags     map[string]string
	Default  any
	Schema   any
	RealName string
	Rules    map[string]*Rule

	IsMAP,
	IsSlice,
	IsStruct,
	IsPointer bool

	SliceType,
	MapKeyType,
	MapValueType *Fielder

	SkipValidate bool // default: false
	Walk         bool // default: true -> deep validation
	Recurcive    bool // default: false -> for embed struct

	Children      map[string]*Fielder //
	FieldsByIndex map[int]string      //
	SuperIndex    *int                // if a field to a struct

	Required bool // default: false

	Nullable bool // default: true

	SkipError bool // default: false
	OmitEmpty bool // default: false
}

func GetFielder

func GetFielder(key string) *Fielder

func ParseSchema

func ParseSchema(schema any) *Fielder

usage:

c3po.ParseSchema(struct{}) => struct{}
c3po.ParseSchema(&struct{}) => *struct{}
c3po.ParseSchema(&struct{Field:Value}) => *struct{Field: value} // with default value

type Schema struct{
	Field `c3po:"-"`				// omit this field
	Field `c3po:"name"`				// string: name of validation		(default realName)
	Field `c3po:"walk"`				// bool: deep validation			(default true)
	Field `c3po:"escape"`			// bool: escape html value			(default false)
	Field `c3po:"required"`			// bool:		...			 		(default false)
	Field `c3po:"nullable"`			// bool: if true, allow nil value	(default true)
	Field `c3po:"recursive"`		// bool: for embbed data 			(default false)
	Field `c3po:"skiperr"`			// bool: omit on error				(default false)
	Field `c3po:"skip"`				// bool: set value without validate	(default false)
	Field `c3po:"min=18"`			// numbers only (int8, 16..., float32, ...)
	Field `c3po:"max=65"`			// numbers only (int8, 16..., float32, ...)
	Field `c3po:"minlength=1"`		// if a value can len, is valid. else skip
	Field `c3po:"maxlength=100"`	// if a value can len, is valid. else skip
}

func ParseSchemaWithTag

func ParseSchemaWithTag(tagKey string, schema any) *Fielder

func (*Fielder) CheckSchPtr

func (f *Fielder) CheckSchPtr(r reflect.Value) any

func (*Fielder) Decode

func (f *Fielder) Decode(data any) Schema

func (*Fielder) ExecRules

func (f *Fielder) ExecRules(sch reflect.Value) (reflect.Value, any)

func (*Fielder) New

func (f *Fielder) New() reflect.Value

func (*Fielder) String

func (f *Fielder) String() string

func (*Fielder) ToMap

func (f *Fielder) ToMap() map[string]any

type Rule

type Rule struct {
	Name           string //
	Value          string //
	Message        string // ex.: {field} require a value >= 18
	Validate       func(rv reflect.Value, rule string) bool
	BeforeSetValue bool // exec after set value
}

func GetRule

func GetRule(rule string) *Rule

func (*Rule) ToMap

func (r *Rule) ToMap() map[string]any

type Schema

type Schema interface {
	Value() any
	Errors() []error
	HasErrors() bool
}

func Validate

func Validate(sch, data any) Schema

use 'validate' in tags

type User struct{
	Name string `validate:"minlen=4"`
	Age int `validate:"min=18"`
}
sch := c3po.Validate(&User{},map[string]any{})
if sch.HasErrors(){
	err := sch.Errors()
	....
} else {
	user := sch.Value().(*User)
}

func ValidateSchema

func ValidateSchema(key string, data any) Schema

type ValidationError

type ValidationError struct {
	Rule  *Rule
	Field string
}

func (ValidationError) Error

func (v ValidationError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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