Home

Awesome

Filter

GitHub tag (latest SemVer) Actions Status Coverage Status Go Report Card Go Reference

filter - provide filtering, sanitizing, and conversion of Golang data.

中文说明请查看 README.zh-CN

GoDoc

NOTE: To filter and validate Map, Struct data. Please use gookit/validate

Install

go get github.com/gookit/filter

Func Usage

Quick usage:

str := filter.MustString(23) // "23"

intVal, err := filter.Int("20") // int(20)
strings := filter.Str2Slice("a,b, c", ",") // []string{"a", "b", "c"}

Filtration

Filtering data:

data := map[string]any{
    "name":     " inhere ",
    "age":      "50",
    "money":    "50.34",
    // 
    "remember": "yes",
    //
    "sub1": []string{"1", "2"},
    "tags": "go;lib",
    "str1": " word ",
    "ids":  []int{1, 2, 2, 1},
}
f := filter.New(data)
f.AddRule("money", "float")
f.AddRule("remember", "bool")
f.AddRule("sub1", "strings2ints")
f.AddRule("tags", "str2arr:;")
f.AddRule("ids", "unique")
f.AddRule("str1", "ltrim|rtrim")
f.AddRule("not-exist", "unique")
// add multi
f.AddRules(map[string]string{
    "age": "trim|int",
    "name": "trim|ucFirst",
})

// apply all added rules for data.
f.Filtering() 

// get filtered data
newData := f.CleanData()
fmt.Printf("%#v\n", newData)
// f.BindStruct(&user)

Output:

map[string]interface {}{
    "remember":true, 
    "sub1":[]int{1, 2}, 
    "tags":[]string{"go", "lib"}, 
    "ids":[]int{2, 1}, 
    "str1":"word", 
    "name":"INHERE", 
    "age":50, 
    "money":50.34
}

Filters & Converters

License

MIT