repo
stringlengths 5
67
| sha
stringlengths 40
40
| path
stringlengths 4
234
| url
stringlengths 85
339
| language
stringclasses 6
values | split
stringclasses 3
values | doc
stringlengths 3
51.2k
| sign
stringlengths 5
8.01k
| problem
stringlengths 13
51.2k
| output
stringlengths 0
3.87M
|
---|---|---|---|---|---|---|---|---|---|
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | translations/zh_tw/zh_tw.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/translations/zh_tw/zh_tw.go#L18-L1336 | go | train | // RegisterDefaultTranslations registers a set of default translations
// for all built in tag's in validator; you may add your own as desired. | func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) | // RegisterDefaultTranslations registers a set of default translations
// for all built in tag's in validator; you may add your own as desired.
func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) | {
translations := []struct {
tag string
translation string
override bool
customRegisFunc validator.RegisterTranslationsFunc
customTransFunc validator.TranslationFunc
}{
{
tag: "required",
translation: "{0}為必填欄位",
override: false,
},
{
tag: "len",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("len-string", "{0}長度必須為{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("len-string-character", "{0}字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("len-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("len-number", "{0}必須等於{1}", false); err != nil {
return
}
if err = ut.Add("len-items", "{0}必須包含{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("len-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("len-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("len-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("len-items", fe.Field(), c)
default:
t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "min",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("min-string", "{0}長度必須至少為{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("min-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("min-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("min-number", "{0}最小只能為{1}", false); err != nil {
return
}
if err = ut.Add("min-items", "{0}必須至少包含{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("min-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("min-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("min-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("min-items", fe.Field(), c)
default:
t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "max",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("max-string", "{0}長度不能超過{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("max-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("max-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("max-number", "{0}必須小於或等於{1}", false); err != nil {
return
}
if err = ut.Add("max-items", "{0}最多只能包含{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("max-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("max-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("max-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("max-items", fe.Field(), c)
default:
t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "eq",
translation: "{0}不等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ne",
translation: "{0}不能等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "lt",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("lt-string", "{0}長度必須小於{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("lt-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("lt-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lt-number", "{0}必須小於{1}", false); err != nil {
return
}
if err = ut.Add("lt-items", "{0}必須包含少於{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("lt-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("lt-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lt-datetime", "{0}必須小於目前日期和時間", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lt-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lt-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag())
}
t, err = ut.T("lt-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "lte",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("lte-string", "{0}長度不能超過{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("lte-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("lte-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lte-number", "{0}必須小於或等於{1}", false); err != nil {
return
}
if err = ut.Add("lte-items", "{0}最多只能包含{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("lte-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lte-datetime", "{0}必須小於或等於目前日期和時間", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lte-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lte-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag())
}
t, err = ut.T("lte-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "gt",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("gt-string", "{0}長度必須大於{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("gt-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("gt-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gt-number", "{0}必須大於{1}", false); err != nil {
return
}
if err = ut.Add("gt-items", "{0}必須大於{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("gt-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("gt-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gt-datetime", "{0}必須大於目前日期和時間", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gt-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gt-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag())
}
t, err = ut.T("gt-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "gte",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("gte-string", "{0}長度必須至少為{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("gte-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("gte-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gte-number", "{0}必須大於或等於{1}", false); err != nil {
return
}
if err = ut.Add("gte-items", "{0}必須至少包含{1}", false); err != nil {
return
}
//if err = ut.AddCardinal("gte-items-item", "{0}項", locales.PluralRuleOne, false); err != nil {
// return
//}
if err = ut.AddCardinal("gte-items-item", "{0}項", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gte-datetime", "{0}必須大於或等於目前日期和時間", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gte-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gte-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag())
}
t, err = ut.T("gte-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("警告: 翻譯欄位錯誤: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "eqfield",
translation: "{0}必須等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "eqcsfield",
translation: "{0}必須等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "necsfield",
translation: "{0}不能等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtcsfield",
translation: "{0}必須大於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtecsfield",
translation: "{0}必須大於或等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltcsfield",
translation: "{0}必須小於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltecsfield",
translation: "{0}必須小於或等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "nefield",
translation: "{0}不能等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtfield",
translation: "{0}必須大於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtefield",
translation: "{0}必須大於或等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltfield",
translation: "{0}必須小於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltefield",
translation: "{0}必須小於或等於{1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "alpha",
translation: "{0}只能包含字母",
override: false,
},
{
tag: "alphanum",
translation: "{0}只能包含字母和數字",
override: false,
},
{
tag: "numeric",
translation: "{0}必須是一個有效的數值",
override: false,
},
{
tag: "number",
translation: "{0}必須是一個有效的數字",
override: false,
},
{
tag: "hexadecimal",
translation: "{0}必須是一個有效的十六進制",
override: false,
},
{
tag: "hexcolor",
translation: "{0}必須是一個有效的十六進制顏色",
override: false,
},
{
tag: "rgb",
translation: "{0}必須是一個有效的RGB顏色",
override: false,
},
{
tag: "rgba",
translation: "{0}必須是一個有效的RGBA顏色",
override: false,
},
{
tag: "hsl",
translation: "{0}必須是一個有效的HSL顏色",
override: false,
},
{
tag: "hsla",
translation: "{0}必須是一個有效的HSLA顏色",
override: false,
},
{
tag: "email",
translation: "{0}必須是一個有效的信箱",
override: false,
},
{
tag: "url",
translation: "{0}必須是一個有效的URL",
override: false,
},
{
tag: "uri",
translation: "{0}必須是一個有效的URI",
override: false,
},
{
tag: "base64",
translation: "{0}必須是一個有效的Base64字元串",
override: false,
},
{
tag: "contains",
translation: "{0}必須包含文字'{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "containsany",
translation: "{0}必須包含至少一個以下字元'{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludes",
translation: "{0}不能包含文字'{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludesall",
translation: "{0}不能包含以下任何字元'{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludesrune",
translation: "{0}不能包含'{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "isbn",
translation: "{0}必須是一個有效的ISBN編號",
override: false,
},
{
tag: "isbn10",
translation: "{0}必須是一個有效的ISBN-10編號",
override: false,
},
{
tag: "isbn13",
translation: "{0}必須是一個有效的ISBN-13編號",
override: false,
},
{
tag: "uuid",
translation: "{0}必須是一個有效的UUID",
override: false,
},
{
tag: "uuid3",
translation: "{0}必須是一個有效的V3 UUID",
override: false,
},
{
tag: "uuid4",
translation: "{0}必須是一個有效的V4 UUID",
override: false,
},
{
tag: "uuid5",
translation: "{0}必須是一個有效的V5 UUID",
override: false,
},
{
tag: "ascii",
translation: "{0}必須只包含ascii字元",
override: false,
},
{
tag: "printascii",
translation: "{0}必須只包含可輸出的ascii字元",
override: false,
},
{
tag: "multibyte",
translation: "{0}必須包含多個字元",
override: false,
},
{
tag: "datauri",
translation: "{0}必須包含有效的數據URI",
override: false,
},
{
tag: "latitude",
translation: "{0}必須包含有效的緯度座標",
override: false,
},
{
tag: "longitude",
translation: "{0}必須包含有效的經度座標",
override: false,
},
{
tag: "ssn",
translation: "{0}必須是一個有效的社會安全編號(SSN)",
override: false,
},
{
tag: "ipv4",
translation: "{0}必須是一個有效的IPv4地址",
override: false,
},
{
tag: "ipv6",
translation: "{0}必須是一個有效的IPv6地址",
override: false,
},
{
tag: "ip",
translation: "{0}必須是一個有效的IP地址",
override: false,
},
{
tag: "cidr",
translation: "{0}必須是一個有效的無類別域間路由(CIDR)",
override: false,
},
{
tag: "cidrv4",
translation: "{0}必須是一个包含IPv4地址的有效無類別域間路由(CIDR)",
override: false,
},
{
tag: "cidrv6",
translation: "{0}必須是一个包含IPv6地址的有效無類別域間路由(CIDR)",
override: false,
},
{
tag: "tcp_addr",
translation: "{0}必須是一個有效的TCP地址",
override: false,
},
{
tag: "tcp4_addr",
translation: "{0}必須是一個有效的IPv4 TCP地址",
override: false,
},
{
tag: "tcp6_addr",
translation: "{0}必須是一個有效的IPv6 TCP地址",
override: false,
},
{
tag: "udp_addr",
translation: "{0}必須是一個有效的UDP地址",
override: false,
},
{
tag: "udp4_addr",
translation: "{0}必須是一個有效的IPv4 UDP地址",
override: false,
},
{
tag: "udp6_addr",
translation: "{0}必須是一個有效的IPv6 UDP地址",
override: false,
},
{
tag: "ip_addr",
translation: "{0}必須是一個有效的IP地址",
override: false,
},
{
tag: "ip4_addr",
translation: "{0}必須是一個有效的IPv4地址",
override: false,
},
{
tag: "ip6_addr",
translation: "{0}必須是一個有效的IPv6地址",
override: false,
},
{
tag: "unix_addr",
translation: "{0}必須是一個有效的UNIX地址",
override: false,
},
{
tag: "mac",
translation: "{0}必須是一個有效的MAC地址",
override: false,
},
{
tag: "iscolor",
translation: "{0}必須是一個有效的顏色",
override: false,
},
{
tag: "oneof",
translation: "{0}必須是[{1}]中的一個",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
s, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("警告: 翻譯欄位錯誤: %#v", fe)
return fe.(error).Error()
}
return s
},
},
}
for _, t := range translations {
if t.customTransFunc != nil && t.customRegisFunc != nil {
err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc)
} else if t.customTransFunc != nil && t.customRegisFunc == nil {
err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc)
} else if t.customTransFunc == nil && t.customRegisFunc != nil {
err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc)
} else {
err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc)
}
if err != nil {
return
}
}
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | _examples/struct-level/main.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/_examples/struct-level/main.go#L99-L109 | go | train | // UserStructLevelValidation contains custom struct level validations that don't always
// make sense at the field validation level. For Example this function validates that either
// FirstName or LastName exist; could have done that with a custom field validation but then
// would have had to add it to both fields duplicating the logic + overhead, this way it's
// only validated once.
//
// NOTE: you may ask why wouldn't I just do this outside of validator, because doing this way
// hooks right into validator and you can combine with validation tags and still have a
// common error output format. | func UserStructLevelValidation(sl validator.StructLevel) | // UserStructLevelValidation contains custom struct level validations that don't always
// make sense at the field validation level. For Example this function validates that either
// FirstName or LastName exist; could have done that with a custom field validation but then
// would have had to add it to both fields duplicating the logic + overhead, this way it's
// only validated once.
//
// NOTE: you may ask why wouldn't I just do this outside of validator, because doing this way
// hooks right into validator and you can combine with validation tags and still have a
// common error output format.
func UserStructLevelValidation(sl validator.StructLevel) | {
user := sl.Current().Interface().(User)
if len(user.FirstName) == 0 && len(user.LastName) == 0 {
sl.ReportError(user.FirstName, "FirstName", "fname", "fnameorlname", "")
sl.ReportError(user.LastName, "LastName", "lname", "fnameorlname", "")
}
// plus can do more, even with different tag than "fnameorlname"
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | _examples/custom/main.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/_examples/custom/main.go#L39-L51 | go | train | // ValidateValuer implements validator.CustomTypeFunc | func ValidateValuer(field reflect.Value) interface{} | // ValidateValuer implements validator.CustomTypeFunc
func ValidateValuer(field reflect.Value) interface{} | {
if valuer, ok := field.Interface().(driver.Valuer); ok {
val, err := valuer.Value()
if err == nil {
return val
}
// handle the error how you want
}
return nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L26-L33 | go | train | // Error returns InvalidValidationError message | func (e *InvalidValidationError) Error() string | // Error returns InvalidValidationError message
func (e *InvalidValidationError) Error() string | {
if e.Type == nil {
return "validator: (nil)"
}
return "validator: (nil " + e.Type.String() + ")"
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L43-L57 | go | train | // Error is intended for use in development + debugging and not intended to be a production error message.
// It allows ValidationErrors to subscribe to the Error interface.
// All information to create an error message specific to your application is contained within
// the FieldError found within the ValidationErrors array | func (ve ValidationErrors) Error() string | // Error is intended for use in development + debugging and not intended to be a production error message.
// It allows ValidationErrors to subscribe to the Error interface.
// All information to create an error message specific to your application is contained within
// the FieldError found within the ValidationErrors array
func (ve ValidationErrors) Error() string | {
buff := bytes.NewBufferString("")
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
buff.WriteString(fe.Error())
buff.WriteString("\n")
}
return strings.TrimSpace(buff.String())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L60-L80 | go | train | // Translate translates all of the ValidationErrors | func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations | // Translate translates all of the ValidationErrors
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations | {
trans := make(ValidationErrorsTranslations)
var fe *fieldError
for i := 0; i < len(ve); i++ {
fe = ve[i].(*fieldError)
// // in case an Anonymous struct was used, ensure that the key
// // would be 'Username' instead of ".Username"
// if len(fe.ns) > 0 && fe.ns[:1] == "." {
// trans[fe.ns[1:]] = fe.Translate(ut)
// continue
// }
trans[fe.ns] = fe.Translate(ut)
}
return trans
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L206-L219 | go | train | // Field returns the fields name with the tag name taking precedence over the
// fields actual name. | func (fe *fieldError) Field() string | // Field returns the fields name with the tag name taking precedence over the
// fields actual name.
func (fe *fieldError) Field() string | {
return fe.ns[len(fe.ns)-int(fe.fieldLen):]
// // return fe.field
// fld := fe.ns[len(fe.ns)-int(fe.fieldLen):]
// log.Println("FLD:", fld)
// if len(fld) > 0 && fld[:1] == "." {
// return fld[1:]
// }
// return fld
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L222-L225 | go | train | // returns the fields actual name from the struct, when able to determine. | func (fe *fieldError) StructField() string | // returns the fields actual name from the struct, when able to determine.
func (fe *fieldError) StructField() string | {
// return fe.structField
return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):]
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L250-L252 | go | train | // Error returns the fieldError's error message | func (fe *fieldError) Error() string | // Error returns the fieldError's error message
func (fe *fieldError) Error() string | {
return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | errors.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L259-L272 | go | train | // Translate returns the FieldError's translated error
// from the provided 'ut.Translator' and registered 'TranslationFunc'
//
// NOTE: is not registered translation can be found it returns the same
// as calling fe.Error() | func (fe *fieldError) Translate(ut ut.Translator) string | // Translate returns the FieldError's translated error
// from the provided 'ut.Translator' and registered 'TranslationFunc'
//
// NOTE: is not registered translation can be found it returns the same
// as calling fe.Error()
func (fe *fieldError) Translate(ut ut.Translator) string | {
m, ok := fe.v.transTagFunc[ut]
if !ok {
return fe.Error()
}
fn, ok := m[fe.tag]
if !ok {
return fe.Error()
}
return fn(ut, fe)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | non-standard/validators/notblank.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/non-standard/validators/notblank.go#L12-L25 | go | train | // NotBlank is the validation function for validating if the current field
// has a value or length greater than zero, or is not a space only string. | func NotBlank(fl validator.FieldLevel) bool | // NotBlank is the validation function for validating if the current field
// has a value or length greater than zero, or is not a space only string.
func NotBlank(fl validator.FieldLevel) bool | {
field := fl.Field()
switch field.Kind() {
case reflect.String:
return len(strings.TrimSpace(field.String())) > 0
case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array:
return field.Len() > 0
case reflect.Ptr, reflect.Interface, reflect.Func:
return !field.IsNil()
default:
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L30-L37 | go | train | // wrapFunc wraps noramal Func makes it compatible with FuncCtx | func wrapFunc(fn Func) FuncCtx | // wrapFunc wraps noramal Func makes it compatible with FuncCtx
func wrapFunc(fn Func) FuncCtx | {
if fn == nil {
return nil // be sure not to wrap a bad function.
}
return func(ctx context.Context, fl FieldLevel) bool {
return fn(fl)
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L220-L243 | go | train | // isUnique is the validation function for validating if each array|slice|map value is unique | func isUnique(fl FieldLevel) bool | // isUnique is the validation function for validating if each array|slice|map value is unique
func isUnique(fl FieldLevel) bool | {
field := fl.Field()
v := reflect.ValueOf(struct{}{})
switch field.Kind() {
case reflect.Slice, reflect.Array:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for i := 0; i < field.Len(); i++ {
m.SetMapIndex(field.Index(i), v)
}
return field.Len() == m.Len()
case reflect.Map:
m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
for _, k := range field.MapKeys() {
m.SetMapIndex(field.MapIndex(k), v)
}
return field.Len() == m.Len()
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L246-L251 | go | train | // IsMAC is the validation function for validating if the field's value is a valid MAC address. | func isMAC(fl FieldLevel) bool | // IsMAC is the validation function for validating if the field's value is a valid MAC address.
func isMAC(fl FieldLevel) bool | {
_, err := net.ParseMAC(fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L254-L259 | go | train | // IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. | func isCIDRv4(fl FieldLevel) bool | // IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
func isCIDRv4(fl FieldLevel) bool | {
ip, _, err := net.ParseCIDR(fl.Field().String())
return err == nil && ip.To4() != nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L270-L275 | go | train | // IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. | func isCIDR(fl FieldLevel) bool | // IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
func isCIDR(fl FieldLevel) bool | {
_, _, err := net.ParseCIDR(fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L286-L291 | go | train | // IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. | func isIPv6(fl FieldLevel) bool | // IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
func isIPv6(fl FieldLevel) bool | {
ip := net.ParseIP(fl.Field().String())
return ip != nil && ip.To4() == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L294-L299 | go | train | // IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. | func isIP(fl FieldLevel) bool | // IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
func isIP(fl FieldLevel) bool | {
ip := net.ParseIP(fl.Field().String())
return ip != nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L302-L311 | go | train | // IsSSN is the validation function for validating if the field's value is a valid SSN. | func isSSN(fl FieldLevel) bool | // IsSSN is the validation function for validating if the field's value is a valid SSN.
func isSSN(fl FieldLevel) bool | {
field := fl.Field()
if field.Len() != 11 {
return false
}
return sSNRegex.MatchString(field.String())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L314-L334 | go | train | // IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate. | func isLongitude(fl FieldLevel) bool | // IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate.
func isLongitude(fl FieldLevel) bool | {
field := fl.Field()
var v string
switch field.Kind() {
case reflect.String:
v = field.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v = strconv.FormatInt(field.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = strconv.FormatUint(field.Uint(), 10)
case reflect.Float32:
v = strconv.FormatFloat(field.Float(), 'f', -1, 32)
case reflect.Float64:
v = strconv.FormatFloat(field.Float(), 'f', -1, 64)
default:
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
return longitudeRegex.MatchString(v)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L360-L373 | go | train | // IsDataURI is the validation function for validating if the field's value is a valid data URI. | func isDataURI(fl FieldLevel) bool | // IsDataURI is the validation function for validating if the field's value is a valid data URI.
func isDataURI(fl FieldLevel) bool | {
uri := strings.SplitN(fl.Field().String(), ",", 2)
if len(uri) != 2 {
return false
}
if !dataURIRegex.MatchString(uri[0]) {
return false
}
return base64Regex.MatchString(uri[1])
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L376-L385 | go | train | // HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. | func hasMultiByteCharacter(fl FieldLevel) bool | // HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character.
func hasMultiByteCharacter(fl FieldLevel) bool | {
field := fl.Field()
if field.Len() == 0 {
return true
}
return multibyteRegex.MatchString(field.String())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L443-L461 | go | train | // IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. | func isISBN13(fl FieldLevel) bool | // IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN.
func isISBN13(fl FieldLevel) bool | {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4)
if !iSBN13Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
factor := []int32{1, 3}
for i = 0; i < 12; i++ {
checksum += factor[i%2] * int32(s[i]-'0')
}
return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L464-L486 | go | train | // IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. | func isISBN10(fl FieldLevel) bool | // IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN.
func isISBN10(fl FieldLevel) bool | {
s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3)
if !iSBN10Regex.MatchString(s) {
return false
}
var checksum int32
var i int32
for i = 0; i < 9; i++ {
checksum += (i + 1) * int32(s[i]-'0')
}
if s[9] == 'X' {
checksum += 10 * 10
} else {
checksum += 10 * int32(s[9]-'0')
}
return checksum%11 == 0
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L489-L503 | go | train | // IsEthereumAddress is the validation function for validating if the field's value is a valid ethereum address based currently only on the format | func isEthereumAddress(fl FieldLevel) bool | // IsEthereumAddress is the validation function for validating if the field's value is a valid ethereum address based currently only on the format
func isEthereumAddress(fl FieldLevel) bool | {
address := fl.Field().String()
if !ethAddressRegex.MatchString(address) {
return false
}
if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) {
return true
}
// checksum validation is blocked by https://github.com/golang/crypto/pull/28
return true
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L506-L540 | go | train | // IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address | func isBitcoinAddress(fl FieldLevel) bool | // IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address
func isBitcoinAddress(fl FieldLevel) bool | {
address := fl.Field().String()
if !btcAddressRegex.MatchString(address) {
return false
}
alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
decode := [25]byte{}
for _, n := range []byte(address) {
d := bytes.IndexByte(alphabet, n)
for i := 24; i >= 0; i-- {
d += 58 * int(decode[i])
decode[i] = byte(d % 256)
d /= 256
}
}
h := sha256.New()
_, _ = h.Write(decode[:21])
d := h.Sum([]byte{})
h = sha256.New()
_, _ = h.Write(d)
validchecksum := [4]byte{}
computedchecksum := [4]byte{}
copy(computedchecksum[:], h.Sum(d[:0]))
copy(validchecksum[:], decode[21:])
return validchecksum == computedchecksum
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L543-L620 | go | train | // IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address | func isBitcoinBech32Address(fl FieldLevel) bool | // IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address
func isBitcoinBech32Address(fl FieldLevel) bool | {
address := fl.Field().String()
if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) {
return false
}
am := len(address) % 8
if am == 0 || am == 3 || am == 5 {
return false
}
address = strings.ToLower(address)
alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc
addr := address[3:]
dp := make([]int, 0, len(addr))
for _, c := range addr {
dp = append(dp, strings.IndexRune(alphabet, c))
}
ver := dp[0]
if ver < 0 || ver > 16 {
return false
}
if ver == 0 {
if len(address) != 42 && len(address) != 62 {
return false
}
}
values := append(hr, dp...)
GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}
p := 1
for _, v := range values {
b := p >> 25
p = (p&0x1ffffff)<<5 ^ v
for i := 0; i < 5; i++ {
if (b>>uint(i))&1 == 1 {
p ^= GEN[i]
}
}
}
if p != 1 {
return false
}
b := uint(0)
acc := 0
mv := (1 << 5) - 1
var sw []int
for _, v := range dp[1 : len(dp)-6] {
acc = (acc << 5) | v
b += 5
for b >= 8 {
b -= 8
sw = append(sw, (acc>>b)&mv)
}
}
if len(sw) < 2 || len(sw) > 40 {
return false
}
return true
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L638-L643 | go | train | // ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. | func containsRune(fl FieldLevel) bool | // ContainsRune is the validation function for validating that the field's value contains the rune specified within the param.
func containsRune(fl FieldLevel) bool | {
r, _ := utf8.DecodeRuneInString(fl.Param())
return strings.ContainsRune(fl.Field().String(), r)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L646-L648 | go | train | // ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. | func containsAny(fl FieldLevel) bool | // ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param.
func containsAny(fl FieldLevel) bool | {
return strings.ContainsAny(fl.Field().String(), fl.Param())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L651-L653 | go | train | // Contains is the validation function for validating that the field's value contains the text specified within the param. | func contains(fl FieldLevel) bool | // Contains is the validation function for validating that the field's value contains the text specified within the param.
func contains(fl FieldLevel) bool | {
return strings.Contains(fl.Field().String(), fl.Param())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L656-L658 | go | train | // StartsWith is the validation function for validating that the field's value starts with the text specified within the param. | func startsWith(fl FieldLevel) bool | // StartsWith is the validation function for validating that the field's value starts with the text specified within the param.
func startsWith(fl FieldLevel) bool | {
return strings.HasPrefix(fl.Field().String(), fl.Param())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L661-L663 | go | train | // EndsWith is the validation function for validating that the field's value ends with the text specified within the param. | func endsWith(fl FieldLevel) bool | // EndsWith is the validation function for validating that the field's value ends with the text specified within the param.
func endsWith(fl FieldLevel) bool | {
return strings.HasSuffix(fl.Field().String(), fl.Param())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L666-L676 | go | train | // FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. | func fieldContains(fl FieldLevel) bool | // FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value.
func fieldContains(fl FieldLevel) bool | {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return false
}
return strings.Contains(field.String(), currentField.String())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L679-L688 | go | train | // FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value. | func fieldExcludes(fl FieldLevel) bool | // FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value.
func fieldExcludes(fl FieldLevel) bool | {
field := fl.Field()
currentField, _, ok := fl.GetStructFieldOK()
if !ok {
return true
}
return !strings.Contains(field.String(), currentField.String())
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L981-L1025 | go | train | // IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. | func isEqCrossStructField(fl FieldLevel) bool | // IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value.
func isEqCrossStructField(fl FieldLevel) bool | {
field := fl.Field()
kind := field.Kind()
topField, topKind, ok := fl.GetStructFieldOK()
if !ok || topKind != kind {
return false
}
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return topField.Int() == field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return topField.Uint() == field.Uint()
case reflect.Float32, reflect.Float64:
return topField.Float() == field.Float()
case reflect.Slice, reflect.Map, reflect.Array:
return int64(topField.Len()) == int64(field.Len())
case reflect.Struct:
fieldType := field.Type()
// Not Same underlying type i.e. struct and time
if fieldType != topField.Type() {
return false
}
if fieldType == timeType {
t := field.Interface().(time.Time)
fieldTime := topField.Interface().(time.Time)
return fieldTime.Equal(t)
}
}
// default reflect.String:
return topField.String() == field.String()
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1076-L1108 | go | train | // IsEq is the validation function for validating if the current field's value is equal to the param's value. | func isEq(fl FieldLevel) bool | // IsEq is the validation function for validating if the current field's value is equal to the param's value.
func isEq(fl FieldLevel) bool | {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
return field.String() == param
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) == p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() == p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() == p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() == p
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1121-L1147 | go | train | // IsURI is the validation function for validating if the current field's value is a valid URI. | func isURI(fl FieldLevel) bool | // IsURI is the validation function for validating if the current field's value is a valid URI.
func isURI(fl FieldLevel) bool | {
field := fl.Field()
switch field.Kind() {
case reflect.String:
s := field.String()
// checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195
// emulate browser and strip the '#' suffix prior to validation. see issue-#237
if i := strings.Index(s, "#"); i > -1 {
s = s[:i]
}
if len(s) == 0 {
return false
}
_, err := url.ParseRequestURI(s)
return err == nil
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1184-L1199 | go | train | // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. | func isUrnRFC2141(fl FieldLevel) bool | // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
func isUrnRFC2141(fl FieldLevel) bool | {
field := fl.Field()
switch field.Kind() {
case reflect.String:
str := field.String()
_, match := urn.Parse([]byte(str))
return match
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1202-L1216 | go | train | // IsFile is the validation function for validating if the current field's value is a valid file path. | func isFile(fl FieldLevel) bool | // IsFile is the validation function for validating if the current field's value is a valid file path.
func isFile(fl FieldLevel) bool | {
field := fl.Field()
switch field.Kind() {
case reflect.String:
fileInfo, err := os.Stat(field.String())
if err != nil {
return false
}
return !fileInfo.IsDir()
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1254-L1261 | go | train | // IsNumber is the validation function for validating if the current field's value is a valid number. | func isNumber(fl FieldLevel) bool | // IsNumber is the validation function for validating if the current field's value is a valid number.
func isNumber(fl FieldLevel) bool | {
switch fl.Field().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:
return true
default:
return numberRegex.MatchString(fl.Field().String())
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1299-L1314 | go | train | // HasValue is the validation function for validating if the current field's value is not the default static value. | func hasValue(fl FieldLevel) bool | // HasValue is the validation function for validating if the current field's value is not the default static value.
func hasValue(fl FieldLevel) bool | {
field := fl.Field()
switch field.Kind() {
case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
return !field.IsNil()
default:
if fl.(*validate).fldIsPointer && field.Interface() != nil {
return true
}
return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1637-L1681 | go | train | // IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. | func isLte(fl FieldLevel) bool | // IsLte is the validation function for validating if the current field's value is less than or equal to the param's value.
func isLte(fl FieldLevel) bool | {
field := fl.Field()
param := fl.Param()
switch field.Kind() {
case reflect.String:
p := asInt(param)
return int64(utf8.RuneCountInString(field.String())) <= p
case reflect.Slice, reflect.Map, reflect.Array:
p := asInt(param)
return int64(field.Len()) <= p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p := asInt(param)
return field.Int() <= p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p := asUint(param)
return field.Uint() <= p
case reflect.Float32, reflect.Float64:
p := asFloat(param)
return field.Float() <= p
case reflect.Struct:
if field.Type() == timeType {
now := time.Now().UTC()
t := field.Interface().(time.Time)
return t.Before(now) || t.Equal(now)
}
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1733-L1741 | go | train | // IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. | func isTCP4AddrResolvable(fl FieldLevel) bool | // IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address.
func isTCP4AddrResolvable(fl FieldLevel) bool | {
if !isIP4Addr(fl) {
return false
}
_, err := net.ResolveTCPAddr("tcp4", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1792-L1801 | go | train | // IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. | func isUDPAddrResolvable(fl FieldLevel) bool | // IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address.
func isUDPAddrResolvable(fl FieldLevel) bool | {
if !isIP4Addr(fl) && !isIP6Addr(fl) {
return false
}
_, err := net.ResolveUDPAddr("udp", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1804-L1813 | go | train | // IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. | func isIP4AddrResolvable(fl FieldLevel) bool | // IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address.
func isIP4AddrResolvable(fl FieldLevel) bool | {
if !isIPv4(fl) {
return false
}
_, err := net.ResolveIPAddr("ip4", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1816-L1825 | go | train | // IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. | func isIP6AddrResolvable(fl FieldLevel) bool | // IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address.
func isIP6AddrResolvable(fl FieldLevel) bool | {
if !isIPv6(fl) {
return false
}
_, err := net.ResolveIPAddr("ip6", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1828-L1837 | go | train | // IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. | func isIPAddrResolvable(fl FieldLevel) bool | // IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address.
func isIPAddrResolvable(fl FieldLevel) bool | {
if !isIP(fl) {
return false
}
_, err := net.ResolveIPAddr("ip", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | baked_in.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L1840-L1845 | go | train | // IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. | func isUnixAddrResolvable(fl FieldLevel) bool | // IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address.
func isUnixAddrResolvable(fl FieldLevel) bool | {
_, err := net.ResolveUnixAddr("unix", fl.Field().String())
return err == nil
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | translations/en/en.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/translations/en/en.go#L18-L1345 | go | train | // RegisterDefaultTranslations registers a set of default translations
// for all built in tag's in validator; you may add your own as desired. | func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) | // RegisterDefaultTranslations registers a set of default translations
// for all built in tag's in validator; you may add your own as desired.
func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) | {
translations := []struct {
tag string
translation string
override bool
customRegisFunc validator.RegisterTranslationsFunc
customTransFunc validator.TranslationFunc
}{
{
tag: "required",
translation: "{0} is a required field",
override: false,
},
{
tag: "len",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("len-string", "{0} must be {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("len-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("len-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("len-number", "{0} must be equal to {1}", false); err != nil {
return
}
if err = ut.Add("len-items", "{0} must contain {1}", false); err != nil {
return
}
if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("len-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("len-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("len-items", fe.Field(), c)
default:
t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "min",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("min-string", "{0} must be at least {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("min-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("min-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("min-number", "{0} must be {1} or greater", false); err != nil {
return
}
if err = ut.Add("min-items", "{0} must contain at least {1}", false); err != nil {
return
}
if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("min-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("min-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("min-items", fe.Field(), c)
default:
t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "max",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("max-string", "{0} must be a maximum of {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("max-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("max-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("max-number", "{0} must be {1} or less", false); err != nil {
return
}
if err = ut.Add("max-items", "{0} must contain at maximum {1}", false); err != nil {
return
}
if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("max-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var digits uint64
var kind reflect.Kind
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err := strconv.ParseFloat(fe.Param(), 64)
if err != nil {
goto END
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("max-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("max-items", fe.Field(), c)
default:
t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "eq",
translation: "{0} is not equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
fmt.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ne",
translation: "{0} should not be equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
fmt.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "lt",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("lt-string", "{0} must be less than {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("lt-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("lt-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lt-number", "{0} must be less than {1}", false); err != nil {
return
}
if err = ut.Add("lt-items", "{0} must contain less than {1}", false); err != nil {
return
}
if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("lt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lt-datetime", "{0} must be less than the current Date & Time", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lt-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lt-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag())
goto END
}
t, err = ut.T("lt-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "lte",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("lte-string", "{0} must be at maximum {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("lte-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("lte-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lte-number", "{0} must be {1} or less", false); err != nil {
return
}
if err = ut.Add("lte-items", "{0} must contain at maximum {1}", false); err != nil {
return
}
if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("lte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("lte-datetime", "{0} must be less than or equal to the current Date & Time", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lte-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("lte-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag())
goto END
}
t, err = ut.T("lte-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "gt",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("gt-string", "{0} must be greater than {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("gt-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("gt-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gt-number", "{0} must be greater than {1}", false); err != nil {
return
}
if err = ut.Add("gt-items", "{0} must contain more than {1}", false); err != nil {
return
}
if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("gt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gt-datetime", "{0} must be greater than the current Date & Time", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gt-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gt-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag())
goto END
}
t, err = ut.T("gt-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "gte",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("gte-string", "{0} must be at least {1} in length", false); err != nil {
return
}
if err = ut.AddCardinal("gte-string-character", "{0} character", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("gte-string-character", "{0} characters", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gte-number", "{0} must be {1} or greater", false); err != nil {
return
}
if err = ut.Add("gte-items", "{0} must contain at least {1}", false); err != nil {
return
}
if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
return
}
if err = ut.AddCardinal("gte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil {
return
}
if err = ut.Add("gte-datetime", "{0} must be greater than or equal to the current Date & Time", false); err != nil {
return
}
return
},
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
var err error
var t string
var f64 float64
var digits uint64
var kind reflect.Kind
fn := func() (err error) {
if idx := strings.Index(fe.Param(), "."); idx != -1 {
digits = uint64(len(fe.Param()[idx+1:]))
}
f64, err = strconv.ParseFloat(fe.Param(), 64)
return
}
kind = fe.Kind()
if kind == reflect.Ptr {
kind = fe.Type().Elem().Kind()
}
switch kind {
case reflect.String:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gte-string", fe.Field(), c)
case reflect.Slice, reflect.Map, reflect.Array:
var c string
err = fn()
if err != nil {
goto END
}
c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits))
if err != nil {
goto END
}
t, err = ut.T("gte-items", fe.Field(), c)
case reflect.Struct:
if fe.Type() != reflect.TypeOf(time.Time{}) {
err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag())
goto END
}
t, err = ut.T("gte-datetime", fe.Field())
default:
err = fn()
if err != nil {
goto END
}
t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits))
}
END:
if err != nil {
fmt.Printf("warning: error translating FieldError: %s", err)
return fe.(error).Error()
}
return t
},
},
{
tag: "eqfield",
translation: "{0} must be equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "eqcsfield",
translation: "{0} must be equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "necsfield",
translation: "{0} cannot be equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtcsfield",
translation: "{0} must be greater than {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtecsfield",
translation: "{0} must be greater than or equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltcsfield",
translation: "{0} must be less than {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltecsfield",
translation: "{0} must be less than or equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "nefield",
translation: "{0} cannot be equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtfield",
translation: "{0} must be greater than {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "gtefield",
translation: "{0} must be greater than or equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltfield",
translation: "{0} must be less than {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "ltefield",
translation: "{0} must be less than or equal to {1}",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "alpha",
translation: "{0} can only contain alphabetic characters",
override: false,
},
{
tag: "alphanum",
translation: "{0} can only contain alphanumeric characters",
override: false,
},
{
tag: "numeric",
translation: "{0} must be a valid numeric value",
override: false,
},
{
tag: "number",
translation: "{0} must be a valid number",
override: false,
},
{
tag: "hexadecimal",
translation: "{0} must be a valid hexadecimal",
override: false,
},
{
tag: "hexcolor",
translation: "{0} must be a valid HEX color",
override: false,
},
{
tag: "rgb",
translation: "{0} must be a valid RGB color",
override: false,
},
{
tag: "rgba",
translation: "{0} must be a valid RGBA color",
override: false,
},
{
tag: "hsl",
translation: "{0} must be a valid HSL color",
override: false,
},
{
tag: "hsla",
translation: "{0} must be a valid HSLA color",
override: false,
},
{
tag: "email",
translation: "{0} must be a valid email address",
override: false,
},
{
tag: "url",
translation: "{0} must be a valid URL",
override: false,
},
{
tag: "uri",
translation: "{0} must be a valid URI",
override: false,
},
{
tag: "base64",
translation: "{0} must be a valid Base64 string",
override: false,
},
{
tag: "contains",
translation: "{0} must contain the text '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "containsany",
translation: "{0} must contain at least one of the following characters '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludes",
translation: "{0} cannot contain the text '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludesall",
translation: "{0} cannot contain any of the following characters '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludesrune",
translation: "{0} cannot contain the following '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "isbn",
translation: "{0} must be a valid ISBN number",
override: false,
},
{
tag: "isbn10",
translation: "{0} must be a valid ISBN-10 number",
override: false,
},
{
tag: "isbn13",
translation: "{0} must be a valid ISBN-13 number",
override: false,
},
{
tag: "uuid",
translation: "{0} must be a valid UUID",
override: false,
},
{
tag: "uuid3",
translation: "{0} must be a valid version 3 UUID",
override: false,
},
{
tag: "uuid4",
translation: "{0} must be a valid version 4 UUID",
override: false,
},
{
tag: "uuid5",
translation: "{0} must be a valid version 5 UUID",
override: false,
},
{
tag: "ascii",
translation: "{0} must contain only ascii characters",
override: false,
},
{
tag: "printascii",
translation: "{0} must contain only printable ascii characters",
override: false,
},
{
tag: "multibyte",
translation: "{0} must contain multibyte characters",
override: false,
},
{
tag: "datauri",
translation: "{0} must contain a valid Data URI",
override: false,
},
{
tag: "latitude",
translation: "{0} must contain valid latitude coordinates",
override: false,
},
{
tag: "longitude",
translation: "{0} must contain a valid longitude coordinates",
override: false,
},
{
tag: "ssn",
translation: "{0} must be a valid SSN number",
override: false,
},
{
tag: "ipv4",
translation: "{0} must be a valid IPv4 address",
override: false,
},
{
tag: "ipv6",
translation: "{0} must be a valid IPv6 address",
override: false,
},
{
tag: "ip",
translation: "{0} must be a valid IP address",
override: false,
},
{
tag: "cidr",
translation: "{0} must contain a valid CIDR notation",
override: false,
},
{
tag: "cidrv4",
translation: "{0} must contain a valid CIDR notation for an IPv4 address",
override: false,
},
{
tag: "cidrv6",
translation: "{0} must contain a valid CIDR notation for an IPv6 address",
override: false,
},
{
tag: "tcp_addr",
translation: "{0} must be a valid TCP address",
override: false,
},
{
tag: "tcp4_addr",
translation: "{0} must be a valid IPv4 TCP address",
override: false,
},
{
tag: "tcp6_addr",
translation: "{0} must be a valid IPv6 TCP address",
override: false,
},
{
tag: "udp_addr",
translation: "{0} must be a valid UDP address",
override: false,
},
{
tag: "udp4_addr",
translation: "{0} must be a valid IPv4 UDP address",
override: false,
},
{
tag: "udp6_addr",
translation: "{0} must be a valid IPv6 UDP address",
override: false,
},
{
tag: "ip_addr",
translation: "{0} must be a resolvable IP address",
override: false,
},
{
tag: "ip4_addr",
translation: "{0} must be a resolvable IPv4 address",
override: false,
},
{
tag: "ip6_addr",
translation: "{0} must be a resolvable IPv6 address",
override: false,
},
{
tag: "unix_addr",
translation: "{0} must be a resolvable UNIX address",
override: false,
},
{
tag: "mac",
translation: "{0} must contain a valid MAC address",
override: false,
},
{
tag: "unique",
translation: "{0} must contain unique values",
override: false,
},
{
tag: "iscolor",
translation: "{0} must be a valid color",
override: false,
},
{
tag: "oneof",
translation: "{0} must be one of [{1}]",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
s, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return s
},
},
}
for _, t := range translations {
if t.customTransFunc != nil && t.customRegisFunc != nil {
err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc)
} else if t.customTransFunc != nil && t.customRegisFunc == nil {
err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc)
} else if t.customTransFunc == nil && t.customRegisFunc != nil {
err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc)
} else {
err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc)
}
if err != nil {
return
}
}
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | util.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L12-L53 | go | train | // extractTypeInternal gets the actual underlying type of field value.
// It will dive into pointers, customTypes and return you the
// underlying value and it's kind. | func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) | // extractTypeInternal gets the actual underlying type of field value.
// It will dive into pointers, customTypes and return you the
// underlying value and it's kind.
func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) | {
BEGIN:
switch current.Kind() {
case reflect.Ptr:
nullable = true
if current.IsNil() {
return current, reflect.Ptr, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Interface:
nullable = true
if current.IsNil() {
return current, reflect.Interface, nullable
}
current = current.Elem()
goto BEGIN
case reflect.Invalid:
return current, reflect.Invalid, nullable
default:
if v.v.hasCustomFuncs {
if fn, ok := v.v.customFuncs[current.Type()]; ok {
current = reflect.ValueOf(fn(current))
goto BEGIN
}
}
return current, current.Kind(), nullable
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | util.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L60-L221 | go | train | // getStructFieldOKInternal traverses a struct to retrieve a specific field denoted by the provided namespace and
// returns the field, field kind and whether is was successful in retrieving the field at all.
//
// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field
// could not be retrieved because it didn't exist. | func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, found bool) | // getStructFieldOKInternal traverses a struct to retrieve a specific field denoted by the provided namespace and
// returns the field, field kind and whether is was successful in retrieving the field at all.
//
// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field
// could not be retrieved because it didn't exist.
func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, found bool) | {
BEGIN:
current, kind, _ = v.ExtractType(val)
if kind == reflect.Invalid {
return
}
if namespace == "" {
found = true
return
}
switch kind {
case reflect.Ptr, reflect.Interface:
return
case reflect.Struct:
typ := current.Type()
fld := namespace
var ns string
if typ != timeType {
idx := strings.Index(namespace, namespaceSeparator)
if idx != -1 {
fld = namespace[:idx]
ns = namespace[idx+1:]
} else {
ns = ""
}
bracketIdx := strings.Index(fld, leftBracket)
if bracketIdx != -1 {
fld = fld[:bracketIdx]
ns = namespace[bracketIdx:]
}
val = current.FieldByName(fld)
namespace = ns
goto BEGIN
}
case reflect.Array, reflect.Slice:
idx := strings.Index(namespace, leftBracket)
idx2 := strings.Index(namespace, rightBracket)
arrIdx, _ := strconv.Atoi(namespace[idx+1 : idx2])
if arrIdx >= current.Len() {
return current, kind, false
}
startIdx := idx2 + 1
if startIdx < len(namespace) {
if namespace[startIdx:startIdx+1] == namespaceSeparator {
startIdx++
}
}
val = current.Index(arrIdx)
namespace = namespace[startIdx:]
goto BEGIN
case reflect.Map:
idx := strings.Index(namespace, leftBracket) + 1
idx2 := strings.Index(namespace, rightBracket)
endIdx := idx2
if endIdx+1 < len(namespace) {
if namespace[endIdx+1:endIdx+2] == namespaceSeparator {
endIdx++
}
}
key := namespace[idx:idx2]
switch current.Type().Key().Kind() {
case reflect.Int:
i, _ := strconv.Atoi(key)
val = current.MapIndex(reflect.ValueOf(i))
namespace = namespace[endIdx+1:]
case reflect.Int8:
i, _ := strconv.ParseInt(key, 10, 8)
val = current.MapIndex(reflect.ValueOf(int8(i)))
namespace = namespace[endIdx+1:]
case reflect.Int16:
i, _ := strconv.ParseInt(key, 10, 16)
val = current.MapIndex(reflect.ValueOf(int16(i)))
namespace = namespace[endIdx+1:]
case reflect.Int32:
i, _ := strconv.ParseInt(key, 10, 32)
val = current.MapIndex(reflect.ValueOf(int32(i)))
namespace = namespace[endIdx+1:]
case reflect.Int64:
i, _ := strconv.ParseInt(key, 10, 64)
val = current.MapIndex(reflect.ValueOf(i))
namespace = namespace[endIdx+1:]
case reflect.Uint:
i, _ := strconv.ParseUint(key, 10, 0)
val = current.MapIndex(reflect.ValueOf(uint(i)))
namespace = namespace[endIdx+1:]
case reflect.Uint8:
i, _ := strconv.ParseUint(key, 10, 8)
val = current.MapIndex(reflect.ValueOf(uint8(i)))
namespace = namespace[endIdx+1:]
case reflect.Uint16:
i, _ := strconv.ParseUint(key, 10, 16)
val = current.MapIndex(reflect.ValueOf(uint16(i)))
namespace = namespace[endIdx+1:]
case reflect.Uint32:
i, _ := strconv.ParseUint(key, 10, 32)
val = current.MapIndex(reflect.ValueOf(uint32(i)))
namespace = namespace[endIdx+1:]
case reflect.Uint64:
i, _ := strconv.ParseUint(key, 10, 64)
val = current.MapIndex(reflect.ValueOf(i))
namespace = namespace[endIdx+1:]
case reflect.Float32:
f, _ := strconv.ParseFloat(key, 32)
val = current.MapIndex(reflect.ValueOf(float32(f)))
namespace = namespace[endIdx+1:]
case reflect.Float64:
f, _ := strconv.ParseFloat(key, 64)
val = current.MapIndex(reflect.ValueOf(f))
namespace = namespace[endIdx+1:]
case reflect.Bool:
b, _ := strconv.ParseBool(key)
val = current.MapIndex(reflect.ValueOf(b))
namespace = namespace[endIdx+1:]
// reflect.Type = string
default:
val = current.MapIndex(reflect.ValueOf(key))
namespace = namespace[endIdx+1:]
}
goto BEGIN
}
// if got here there was more namespace, cannot go any deeper
panic("Invalid field namespace")
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | util.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L225-L231 | go | train | // asInt returns the parameter as a int64
// or panics if it can't convert | func asInt(param string) int64 | // asInt returns the parameter as a int64
// or panics if it can't convert
func asInt(param string) int64 | {
i, err := strconv.ParseInt(param, 0, 64)
panicIf(err)
return i
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | util.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L235-L241 | go | train | // asUint returns the parameter as a uint64
// or panics if it can't convert | func asUint(param string) uint64 | // asUint returns the parameter as a uint64
// or panics if it can't convert
func asUint(param string) uint64 | {
i, err := strconv.ParseUint(param, 0, 64)
panicIf(err)
return i
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | util.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/util.go#L245-L251 | go | train | // asFloat returns the parameter as a float64
// or panics if it can't convert | func asFloat(param string) float64 | // asFloat returns the parameter as a float64
// or panics if it can't convert
func asFloat(param string) float64 | {
i, err := strconv.ParseFloat(param, 64)
panicIf(err)
return i
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L75-L115 | go | train | // New returns a new instance of 'validate' with sane defaults. | func New() *Validate | // New returns a new instance of 'validate' with sane defaults.
func New() *Validate | {
tc := new(tagCache)
tc.m.Store(make(map[string]*cTag))
sc := new(structCache)
sc.m.Store(make(map[reflect.Type]*cStruct))
v := &Validate{
tagName: defaultTagName,
aliases: make(map[string]string, len(bakedInAliases)),
validations: make(map[string]FuncCtx, len(bakedInValidators)),
tagCache: tc,
structCache: sc,
}
// must copy alias validators for separate validations to be used in each validator instance
for k, val := range bakedInAliases {
v.RegisterAlias(k, val)
}
// must copy validators for separate validations to be used in each instance
for k, val := range bakedInValidators {
// no need to error check here, baked in will always be valid
_ = v.registerValidation(k, wrapFunc(val), true)
}
v.pool = &sync.Pool{
New: func() interface{} {
return &validate{
v: v,
ns: make([]byte, 0, 64),
actualNs: make([]byte, 0, 64),
misc: make([]byte, 32),
}
},
}
return v
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L133-L136 | go | train | // RegisterTagNameFunc registers a function to get alternate names for StructFields.
//
// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
//
// validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
// if name == "-" {
// return ""
// }
// return name
// }) | func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) | // RegisterTagNameFunc registers a function to get alternate names for StructFields.
//
// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
//
// validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
// if name == "-" {
// return ""
// }
// return name
// })
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) | {
v.tagNameFunc = fn
v.hasTagNameFunc = true
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L143-L145 | go | train | // RegisterValidation adds a validation with the given tag
//
// NOTES:
// - if the key already exists, the previous validation function will be replaced.
// - this method is not thread-safe it is intended that these all be registered prior to any validation | func (v *Validate) RegisterValidation(tag string, fn Func) error | // RegisterValidation adds a validation with the given tag
//
// NOTES:
// - if the key already exists, the previous validation function will be replaced.
// - this method is not thread-safe it is intended that these all be registered prior to any validation
func (v *Validate) RegisterValidation(tag string, fn Func) error | {
return v.RegisterValidationCtx(tag, wrapFunc(fn))
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L149-L151 | go | train | // RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation
// allowing context.Context validation support. | func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx) error | // RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation
// allowing context.Context validation support.
func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx) error | {
return v.registerValidation(tag, fn, false)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L179-L188 | go | train | // RegisterAlias registers a mapping of a single validation tag that
// defines a common or complex set of validation(s) to simplify adding validation
// to structs.
//
// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation | func (v *Validate) RegisterAlias(alias, tags string) | // RegisterAlias registers a mapping of a single validation tag that
// defines a common or complex set of validation(s) to simplify adding validation
// to structs.
//
// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation
func (v *Validate) RegisterAlias(alias, tags string) | {
_, ok := restrictedTags[alias]
if ok || strings.ContainsAny(alias, restrictedTagChars) {
panic(fmt.Sprintf(restrictedAliasErr, alias))
}
v.aliases[alias] = tags
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L194-L196 | go | train | // RegisterStructValidation registers a StructLevelFunc against a number of types.
//
// NOTE:
// - this method is not thread-safe it is intended that these all be registered prior to any validation | func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) | // RegisterStructValidation registers a StructLevelFunc against a number of types.
//
// NOTE:
// - this method is not thread-safe it is intended that these all be registered prior to any validation
func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) | {
v.RegisterStructValidationCtx(wrapStructLevelFunc(fn), types...)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L203-L217 | go | train | // RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing
// of contextual validation information via context.Context.
//
// NOTE:
// - this method is not thread-safe it is intended that these all be registered prior to any validation | func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) | // RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing
// of contextual validation information via context.Context.
//
// NOTE:
// - this method is not thread-safe it is intended that these all be registered prior to any validation
func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) | {
if v.structLevelFuncs == nil {
v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx)
}
for _, t := range types {
tv := reflect.ValueOf(t)
if tv.Kind() == reflect.Ptr {
t = reflect.Indirect(tv).Interface()
}
v.structLevelFuncs[reflect.TypeOf(t)] = fn
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L222-L233 | go | train | // RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types
//
// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation | func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) | // RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types
//
// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) | {
if v.customFuncs == nil {
v.customFuncs = make(map[reflect.Type]CustomTypeFunc)
}
for _, t := range types {
v.customFuncs[reflect.TypeOf(t)] = fn
}
v.hasCustomFuncs = true
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L236-L255 | go | train | // RegisterTranslation registers translations against the provided tag. | func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) | // RegisterTranslation registers translations against the provided tag.
func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) | {
if v.transTagFunc == nil {
v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc)
}
if err = registerFn(trans); err != nil {
return
}
m, ok := v.transTagFunc[trans]
if !ok {
m = make(map[string]TranslationFunc)
v.transTagFunc[trans] = m
}
m[tag] = translationFn
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L261-L263 | go | train | // Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) Struct(s interface{}) error | // Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) Struct(s interface{}) error | {
return v.StructCtx(context.Background(), s)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L306-L308 | go | train | // StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates
// nested structs, unless otherwise specified.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error | // StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates
// nested structs, unless otherwise specified.
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error | {
return v.StructFilteredCtx(context.Background(), s, fn)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L316-L345 | go | train | // StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates
// nested structs, unless otherwise specified and also allows passing of contextual validation information via
// context.Context
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) | // StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates
// nested structs, unless otherwise specified and also allows passing of contextual validation information via
// context.Context
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) | {
val := reflect.ValueOf(s)
top := val
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
if val.Kind() != reflect.Struct || val.Type() == timeType {
return &InvalidValidationError{Type: reflect.TypeOf(s)}
}
// good to validate
vd := v.pool.Get().(*validate)
vd.top = top
vd.isPartial = true
vd.ffn = fn
// vd.hasExcludes = false // only need to reset in StructPartial and StructExcept
vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil)
if len(vd.errs) > 0 {
err = vd.errs
vd.errs = nil
}
v.pool.Put(vd)
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L353-L355 | go | train | // StructPartial validates the fields passed in only, ignoring all others.
// Fields may be provided in a namespaced fashion relative to the struct provided
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructPartial(s interface{}, fields ...string) error | // StructPartial validates the fields passed in only, ignoring all others.
// Fields may be provided in a namespaced fashion relative to the struct provided
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructPartial(s interface{}, fields ...string) error | {
return v.StructPartialCtx(context.Background(), s, fields...)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L364-L432 | go | train | // StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual
// validation validation information via context.Context
// Fields may be provided in a namespaced fashion relative to the struct provided
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) | // StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual
// validation validation information via context.Context
// Fields may be provided in a namespaced fashion relative to the struct provided
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) | {
val := reflect.ValueOf(s)
top := val
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
if val.Kind() != reflect.Struct || val.Type() == timeType {
return &InvalidValidationError{Type: reflect.TypeOf(s)}
}
// good to validate
vd := v.pool.Get().(*validate)
vd.top = top
vd.isPartial = true
vd.ffn = nil
vd.hasExcludes = false
vd.includeExclude = make(map[string]struct{})
typ := val.Type()
name := typ.Name()
for _, k := range fields {
flds := strings.Split(k, namespaceSeparator)
if len(flds) > 0 {
vd.misc = append(vd.misc[0:0], name...)
vd.misc = append(vd.misc, '.')
for _, s := range flds {
idx := strings.Index(s, leftBracket)
if idx != -1 {
for idx != -1 {
vd.misc = append(vd.misc, s[:idx]...)
vd.includeExclude[string(vd.misc)] = struct{}{}
idx2 := strings.Index(s, rightBracket)
idx2++
vd.misc = append(vd.misc, s[idx:idx2]...)
vd.includeExclude[string(vd.misc)] = struct{}{}
s = s[idx2:]
idx = strings.Index(s, leftBracket)
}
} else {
vd.misc = append(vd.misc, s...)
vd.includeExclude[string(vd.misc)] = struct{}{}
}
vd.misc = append(vd.misc, '.')
}
}
}
vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil)
if len(vd.errs) > 0 {
err = vd.errs
vd.errs = nil
}
v.pool.Put(vd)
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L440-L442 | go | train | // StructExcept validates all fields except the ones passed in.
// Fields may be provided in a namespaced fashion relative to the struct provided
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructExcept(s interface{}, fields ...string) error | // StructExcept validates all fields except the ones passed in.
// Fields may be provided in a namespaced fashion relative to the struct provided
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructExcept(s interface{}, fields ...string) error | {
return v.StructExceptCtx(context.Background(), s, fields...)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L451-L497 | go | train | // StructExceptCtx validates all fields except the ones passed in and allows passing of contextual
// validation validation information via context.Context
// Fields may be provided in a namespaced fashion relative to the struct provided
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. | func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) | // StructExceptCtx validates all fields except the ones passed in and allows passing of contextual
// validation validation information via context.Context
// Fields may be provided in a namespaced fashion relative to the struct provided
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) | {
val := reflect.ValueOf(s)
top := val
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
if val.Kind() != reflect.Struct || val.Type() == timeType {
return &InvalidValidationError{Type: reflect.TypeOf(s)}
}
// good to validate
vd := v.pool.Get().(*validate)
vd.top = top
vd.isPartial = true
vd.ffn = nil
vd.hasExcludes = true
vd.includeExclude = make(map[string]struct{})
typ := val.Type()
name := typ.Name()
for _, key := range fields {
vd.misc = vd.misc[0:0]
if len(name) > 0 {
vd.misc = append(vd.misc, name...)
vd.misc = append(vd.misc, '.')
}
vd.misc = append(vd.misc, key...)
vd.includeExclude[string(vd.misc)] = struct{}{}
}
vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil)
if len(vd.errs) > 0 {
err = vd.errs
vd.errs = nil
}
v.pool.Put(vd)
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L512-L514 | go | train | // Var validates a single variable using tag style validation.
// eg.
// var i int
// validate.Var(i, "gt=1,lt=10")
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error | func (v *Validate) Var(field interface{}, tag string) error | // Var validates a single variable using tag style validation.
// eg.
// var i int
// validate.Var(i, "gt=1,lt=10")
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error
func (v *Validate) Var(field interface{}, tag string) error | {
return v.VarCtx(context.Background(), field, tag)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L564-L566 | go | train | // VarWithValue validates a single variable, against another variable/field's value using tag style validation
// eg.
// s1 := "abcd"
// s2 := "abcd"
// validate.VarWithValue(s1, s2, "eqcsfield") // returns true
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error | func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error | // VarWithValue validates a single variable, against another variable/field's value using tag style validation
// eg.
// s1 := "abcd"
// s2 := "abcd"
// validate.VarWithValue(s1, s2, "eqcsfield") // returns true
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error
func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error | {
return v.VarWithValueCtx(context.Background(), field, other, tag)
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator_instance.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator_instance.go#L583-L600 | go | train | // VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and
// allows passing of contextual validation validation information via context.Context.
// eg.
// s1 := "abcd"
// s2 := "abcd"
// validate.VarWithValue(s1, s2, "eqcsfield") // returns true
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error | func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) | // VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and
// allows passing of contextual validation validation information via context.Context.
// eg.
// s1 := "abcd"
// s2 := "abcd"
// validate.VarWithValue(s1, s2, "eqcsfield") // returns true
//
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
// if you have a custom type and have registered a custom type handler, so must
// allow it; however unforeseen validations will occur if trying to validate a
// struct that is meant to be passed to 'validate.Struct'
//
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
// validate Array, Slice and maps fields which may contain more than one error
func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) | {
if len(tag) == 0 || tag == skipValidationTag {
return nil
}
ctag := v.fetchCacheTag(tag)
otherVal := reflect.ValueOf(other)
vd := v.pool.Get().(*validate)
vd.top = otherVal
vd.isPartial = false
vd.traverseField(ctx, otherVal, reflect.ValueOf(field), vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag)
if len(vd.errs) > 0 {
err = vd.errs
vd.errs = nil
}
v.pool.Put(vd)
return
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator.go#L33-L93 | go | train | // parent and current will be the same the first run of validateStruct | func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) | // parent and current will be the same the first run of validateStruct
func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) | {
cs, ok := v.v.structCache.Get(typ)
if !ok {
cs = v.v.extractStructCache(current, typ.Name())
}
if len(ns) == 0 && len(cs.name) != 0 {
ns = append(ns, cs.name...)
ns = append(ns, '.')
structNs = append(structNs, cs.name...)
structNs = append(structNs, '.')
}
// ct is nil on top level struct, and structs as fields that have no tag info
// so if nil or if not nil and the structonly tag isn't present
if ct == nil || ct.typeof != typeStructOnly {
var f *cField
for i := 0; i < len(cs.fields); i++ {
f = cs.fields[i]
if v.isPartial {
if v.ffn != nil {
// used with StructFiltered
if v.ffn(append(structNs, f.name...)) {
continue
}
} else {
// used with StructPartial & StructExcept
_, ok = v.includeExclude[string(append(structNs, f.name...))]
if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) {
continue
}
}
}
v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags)
}
}
// check if any struct level validations, after all field validations already checked.
// first iteration will have no info about nostructlevel tag, and is checked prior to
// calling the next iteration of validateStruct called from traverseField.
if cs.fn != nil {
v.slflParent = parent
v.slCurrent = current
v.ns = ns
v.actualNs = structNs
cs.fn(ctx, v)
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | validator.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/validator.go#L96-L475 | go | train | // traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options | func (v *validate) traverseField(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) | // traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options
func (v *validate) traverseField(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) | {
var typ reflect.Type
var kind reflect.Kind
current, kind, v.fldIsPointer = v.extractTypeInternal(current, false)
switch kind {
case reflect.Ptr, reflect.Interface, reflect.Invalid:
if ct == nil {
return
}
if ct.typeof == typeOmitEmpty || ct.typeof == typeIsDefault {
return
}
if ct.hasTag {
v.str1 = string(append(ns, cf.altName...))
if v.v.hasTagNameFunc {
v.str2 = string(append(structNs, cf.name...))
} else {
v.str2 = v.str1
}
if kind == reflect.Invalid {
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: ct.aliasTag,
actualTag: ct.tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
param: ct.param,
kind: kind,
},
)
return
}
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: ct.aliasTag,
actualTag: ct.tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
value: current.Interface(),
param: ct.param,
kind: kind,
typ: current.Type(),
},
)
return
}
case reflect.Struct:
typ = current.Type()
if typ != timeType {
if ct != nil {
if ct.typeof == typeStructOnly {
goto CONTINUE
} else if ct.typeof == typeIsDefault {
// set Field Level fields
v.slflParent = parent
v.flField = current
v.cf = cf
v.ct = ct
if !ct.fn(ctx, v) {
v.str1 = string(append(ns, cf.altName...))
if v.v.hasTagNameFunc {
v.str2 = string(append(structNs, cf.name...))
} else {
v.str2 = v.str1
}
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: ct.aliasTag,
actualTag: ct.tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
value: current.Interface(),
param: ct.param,
kind: kind,
typ: typ,
},
)
return
}
}
ct = ct.next
}
if ct != nil && ct.typeof == typeNoStructLevel {
return
}
CONTINUE:
// if len == 0 then validating using 'Var' or 'VarWithValue'
// Var - doesn't make much sense to do it that way, should call 'Struct', but no harm...
// VarWithField - this allows for validating against each field within the struct against a specific value
// pretty handy in certain situations
if len(cf.name) > 0 {
ns = append(append(ns, cf.altName...), '.')
structNs = append(append(structNs, cf.name...), '.')
}
v.validateStruct(ctx, current, current, typ, ns, structNs, ct)
return
}
}
if !ct.hasTag {
return
}
typ = current.Type()
OUTER:
for {
if ct == nil {
return
}
switch ct.typeof {
case typeOmitEmpty:
// set Field Level fields
v.slflParent = parent
v.flField = current
v.cf = cf
v.ct = ct
if !v.fldIsPointer && !hasValue(v) {
return
}
ct = ct.next
continue
case typeEndKeys:
return
case typeDive:
ct = ct.next
// traverse slice or map here
// or panic ;)
switch kind {
case reflect.Slice, reflect.Array:
var i64 int64
reusableCF := &cField{}
for i := 0; i < current.Len(); i++ {
i64 = int64(i)
v.misc = append(v.misc[0:0], cf.name...)
v.misc = append(v.misc, '[')
v.misc = strconv.AppendInt(v.misc, i64, 10)
v.misc = append(v.misc, ']')
reusableCF.name = string(v.misc)
if cf.namesEqual {
reusableCF.altName = reusableCF.name
} else {
v.misc = append(v.misc[0:0], cf.altName...)
v.misc = append(v.misc, '[')
v.misc = strconv.AppendInt(v.misc, i64, 10)
v.misc = append(v.misc, ']')
reusableCF.altName = string(v.misc)
}
v.traverseField(ctx, parent, current.Index(i), ns, structNs, reusableCF, ct)
}
case reflect.Map:
var pv string
reusableCF := &cField{}
for _, key := range current.MapKeys() {
pv = fmt.Sprintf("%v", key.Interface())
v.misc = append(v.misc[0:0], cf.name...)
v.misc = append(v.misc, '[')
v.misc = append(v.misc, pv...)
v.misc = append(v.misc, ']')
reusableCF.name = string(v.misc)
if cf.namesEqual {
reusableCF.altName = reusableCF.name
} else {
v.misc = append(v.misc[0:0], cf.altName...)
v.misc = append(v.misc, '[')
v.misc = append(v.misc, pv...)
v.misc = append(v.misc, ']')
reusableCF.altName = string(v.misc)
}
if ct != nil && ct.typeof == typeKeys && ct.keys != nil {
v.traverseField(ctx, parent, key, ns, structNs, reusableCF, ct.keys)
// can be nil when just keys being validated
if ct.next != nil {
v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next)
}
} else {
v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct)
}
}
default:
// throw error, if not a slice or map then should not have gotten here
// bad dive tag
panic("dive error! can't dive on a non slice or map")
}
return
case typeOr:
v.misc = v.misc[0:0]
for {
// set Field Level fields
v.slflParent = parent
v.flField = current
v.cf = cf
v.ct = ct
if ct.fn(ctx, v) {
// drain rest of the 'or' values, then continue or leave
for {
ct = ct.next
if ct == nil {
return
}
if ct.typeof != typeOr {
continue OUTER
}
}
}
v.misc = append(v.misc, '|')
v.misc = append(v.misc, ct.tag...)
if ct.hasParam {
v.misc = append(v.misc, '=')
v.misc = append(v.misc, ct.param...)
}
if ct.isBlockEnd || ct.next == nil {
// if we get here, no valid 'or' value and no more tags
v.str1 = string(append(ns, cf.altName...))
if v.v.hasTagNameFunc {
v.str2 = string(append(structNs, cf.name...))
} else {
v.str2 = v.str1
}
if ct.hasAlias {
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: ct.aliasTag,
actualTag: ct.actualAliasTag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
value: current.Interface(),
param: ct.param,
kind: kind,
typ: typ,
},
)
} else {
tVal := string(v.misc)[1:]
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: tVal,
actualTag: tVal,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
value: current.Interface(),
param: ct.param,
kind: kind,
typ: typ,
},
)
}
return
}
ct = ct.next
}
default:
// set Field Level fields
v.slflParent = parent
v.flField = current
v.cf = cf
v.ct = ct
if !ct.fn(ctx, v) {
v.str1 = string(append(ns, cf.altName...))
if v.v.hasTagNameFunc {
v.str2 = string(append(structNs, cf.name...))
} else {
v.str2 = v.str1
}
v.errs = append(v.errs,
&fieldError{
v: v.v,
tag: ct.aliasTag,
actualTag: ct.tag,
ns: v.str1,
structNs: v.str2,
fieldLen: uint8(len(cf.altName)),
structfieldLen: uint8(len(cf.name)),
value: current.Interface(),
param: ct.param,
kind: kind,
typ: typ,
},
)
return
}
ct = ct.next
}
}
} |
go-playground/validator | e25e66164b537d7b3161dfede38466880534e783 | field_level.go | https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/field_level.go#L67-L69 | go | train | // GetStructFieldOK returns Param returns param for validation against current field | func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) | // GetStructFieldOK returns Param returns param for validation against current field
func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) | {
return v.getStructFieldOKInternal(v.slflParent, v.ct.param)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/notificationbee/notificationbeefactory.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/notificationbee/notificationbeefactory.go#L37-L44 | go | train | // New returns a new Bee instance configured with the supplied options. | func (factory *NotificationBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | // New returns a new Bee instance configured with the supplied options.
func (factory *NotificationBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | {
bee := NotificationBee{
Bee: bees.NewBee(name, factory.ID(), description, options),
}
bee.ReloadOptions(options)
return &bee
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/jenkinsbee/jenkinsbeefactory.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/jenkinsbee/jenkinsbeefactory.go#L35-L42 | go | train | // New returns a new Bee instance configured with the supplied options. | func (factory *JenkinsBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | // New returns a new Bee instance configured with the supplied options.
func (factory *JenkinsBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | {
bee := JenkinsBee{
Bee: bees.NewBee(name, factory.ID(), description, options),
}
bee.ReloadOptions(options)
return &bee
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/gitterbee/gitterbeefactory.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/gitterbee/gitterbeefactory.go#L35-L42 | go | train | // New returns a new Bee instance configured with the supplied options. | func (factory *GitterBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | // New returns a new Bee instance configured with the supplied options.
func (factory *GitterBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface | {
bee := GitterBee{
Bee: bees.NewBee(name, factory.ID(), description, options),
}
bee.ReloadOptions(options)
return &bee
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/gitterbee/gitterbeefactory.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/gitterbee/gitterbeefactory.go#L154-L204 | go | train | // Actions describes the available actions provided by this Bee. | func (factory *GitterBeeFactory) Actions() []bees.ActionDescriptor | // Actions describes the available actions provided by this Bee.
func (factory *GitterBeeFactory) Actions() []bees.ActionDescriptor | {
actions := []bees.ActionDescriptor{
{
Namespace: factory.Name(),
Name: "send",
Description: "Sends a message into a room",
Options: []bees.PlaceholderDescriptor{
{
Name: "room",
Description: "Which room to sent the message to",
Type: "string",
Mandatory: true,
},
{
Name: "message",
Description: "Message text",
Type: "string",
Mandatory: true,
},
},
},
{
Namespace: factory.Name(),
Name: "join",
Description: "Join a room on gitter",
Options: []bees.PlaceholderDescriptor{
{
Name: "room",
Description: "Room to join",
Type: "string",
Mandatory: true,
},
},
},
{
Namespace: factory.Name(),
Name: "leave",
Description: "Leave a room on gitter",
Options: []bees.PlaceholderDescriptor{
{
Name: "room",
Description: "Room to leave",
Type: "string",
Mandatory: true,
},
},
},
}
return actions
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | api/resources/actions/actions.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/actions/actions.go#L40-L50 | go | train | // Register this resource with the container to setup all the routes | func (r *ActionResource) Register(container *restful.Container, config smolder.APIConfig, context smolder.APIContextFactory) | // Register this resource with the container to setup all the routes
func (r *ActionResource) Register(container *restful.Container, config smolder.APIConfig, context smolder.APIContextFactory) | {
r.Name = "ActionResource"
r.TypeName = "action"
r.Endpoint = "actions"
r.Doc = "Manage actions"
r.Config = config
r.Context = context
r.Init(container, r)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | api/resources/bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/api/resources/bees/bees.go#L65-L69 | go | train | // Validate checks an incoming request for data errors | func (r *BeeResource) Validate(context smolder.APIContext, data interface{}, request *restful.Request) error | // Validate checks an incoming request for data errors
func (r *BeeResource) Validate(context smolder.APIContext, data interface{}, request *restful.Request) error | {
// ps := data.(*BeePostStruct)
// FIXME
return nil
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/twiliobee/twiliobee.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/twiliobee/twiliobee.go#L41-L59 | go | train | // Action triggers the action passed to it. | func (mod *TwilioBee) Action(action bees.Action) []bees.Placeholder | // Action triggers the action passed to it.
func (mod *TwilioBee) Action(action bees.Action) []bees.Placeholder | {
outs := []bees.Placeholder{}
switch action.Name {
case "send":
body := ""
action.Options.Bind("body", &body)
_, err := twilio.NewMessage(mod.client, mod.fromNumber, mod.toNumber, twilio.Body(body))
if err != nil {
mod.LogErrorf("Error sending twilio SMS: %s", err)
}
default:
panic("Unknown action triggered in " + mod.Name() + ": " + action.Name)
}
return outs
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/twiliobee/twiliobee.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/twiliobee/twiliobee.go#L62-L64 | go | train | // Run executes the Bee's event loop. | func (mod *TwilioBee) Run(eventChan chan bees.Event) | // Run executes the Bee's event loop.
func (mod *TwilioBee) Run(eventChan chan bees.Event) | {
mod.client = twilio.NewClient(mod.accountsid, mod.authtoken)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/twiliobee/twiliobee.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/twiliobee/twiliobee.go#L67-L74 | go | train | // ReloadOptions parses the config options and initializes the Bee. | func (mod *TwilioBee) ReloadOptions(options bees.BeeOptions) | // ReloadOptions parses the config options and initializes the Bee.
func (mod *TwilioBee) ReloadOptions(options bees.BeeOptions) | {
mod.SetOptions(options)
options.Bind("account_sid", &mod.accountsid)
options.Bind("auth_token", &mod.authtoken)
options.Bind("from_number", &mod.fromNumber)
options.Bind("to_number", &mod.toNumber)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L99-L103 | go | train | // RegisterBee gets called by Bees to register themselves. | func RegisterBee(bee BeeInterface) | // RegisterBee gets called by Bees to register themselves.
func RegisterBee(bee BeeInterface) | {
log.Println("Worker bee ready:", bee.Name(), "-", bee.Description())
bees[bee.Name()] = &bee
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L106-L113 | go | train | // GetBee returns a bee with a specific name. | func GetBee(identifier string) *BeeInterface | // GetBee returns a bee with a specific name.
func GetBee(identifier string) *BeeInterface | {
bee, ok := bees[identifier]
if ok {
return bee
}
return nil
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L116-L123 | go | train | // GetBees returns all known bees. | func GetBees() []*BeeInterface | // GetBees returns all known bees.
func GetBees() []*BeeInterface | {
r := []*BeeInterface{}
for _, bee := range bees {
r = append(r, bee)
}
return r
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L126-L144 | go | train | // startBee starts a bee and recovers from panics. | func startBee(bee *BeeInterface, fatals int) | // startBee starts a bee and recovers from panics.
func startBee(bee *BeeInterface, fatals int) | {
if fatals >= 3 {
log.Println("Terminating evil bee", (*bee).Name(), "after", fatals, "failed tries!")
(*bee).Stop()
return
}
(*bee).WaitGroup().Add(1)
defer (*bee).WaitGroup().Done()
defer func(bee *BeeInterface) {
if e := recover(); e != nil {
log.Println("Fatal bee event:", e, fatals)
go startBee(bee, fatals+1)
}
}(bee)
(*bee).Run(eventsIn)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L147-L156 | go | train | // NewBeeInstance sets up a new Bee with supplied config. | func NewBeeInstance(bee BeeConfig) *BeeInterface | // NewBeeInstance sets up a new Bee with supplied config.
func NewBeeInstance(bee BeeConfig) *BeeInterface | {
factory := GetFactory(bee.Class)
if factory == nil {
panic("Unknown bee-class in config file: " + bee.Class)
}
mod := (*factory).New(bee.Name, bee.Description, bee.Options)
RegisterBee(mod)
return &mod
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L166-L175 | go | train | // StartBee starts a bee. | func StartBee(bee BeeConfig) *BeeInterface | // StartBee starts a bee.
func StartBee(bee BeeConfig) *BeeInterface | {
b := NewBeeInstance(bee)
(*b).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(b)
return b
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L178-L185 | go | train | // StartBees starts all registered bees. | func StartBees(beeList []BeeConfig) | // StartBees starts all registered bees.
func StartBees(beeList []BeeConfig) | {
eventsIn = make(chan Event)
go handleEvents()
for _, bee := range beeList {
StartBee(bee)
}
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L188-L196 | go | train | // StopBees stops all bees gracefully. | func StopBees() | // StopBees stops all bees gracefully.
func StopBees() | {
for _, bee := range bees {
log.Println("Stopping bee:", (*bee).Name())
(*bee).Stop()
}
close(eventsIn)
bees = make(map[string]*BeeInterface)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L199-L207 | go | train | // RestartBee restarts a Bee. | func RestartBee(bee *BeeInterface) | // RestartBee restarts a Bee.
func RestartBee(bee *BeeInterface) | {
(*bee).Stop()
(*bee).SetSigChan(make(chan bool))
(*bee).Start()
go func(mod *BeeInterface) {
startBee(mod, 0)
}(bee)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L216-L230 | go | train | // NewBee returns a new bee and sets up sig-channel & waitGroup. | func NewBee(name, factoryName, description string, options []BeeOption) Bee | // NewBee returns a new bee and sets up sig-channel & waitGroup.
func NewBee(name, factoryName, description string, options []BeeOption) Bee | {
c := BeeConfig{
Name: name,
Class: factoryName,
Description: description,
Options: options,
}
b := Bee{
config: c,
SigChan: make(chan bool),
waitGroup: &sync.WaitGroup{},
}
return b
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L301-L311 | go | train | // Stop gracefully stops a Bee. | func (bee *Bee) Stop() | // Stop gracefully stops a Bee.
func (bee *Bee) Stop() | {
if !bee.IsRunning() {
return
}
log.Println(bee.Name(), "stopping gracefully!")
close(bee.SigChan)
bee.waitGroup.Wait()
bee.Running = false
log.Println(bee.Name(), "stopped gracefully!")
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L334-L342 | go | train | // Logln logs args | func (bee *Bee) Logln(args ...interface{}) | // Logln logs args
func (bee *Bee) Logln(args ...interface{}) | {
a := []interface{}{"[" + bee.Name() + "]:"}
for _, v := range args {
a = append(a, v)
}
log.Println(a...)
Log(bee.Name(), fmt.Sprintln(args...), 0)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L345-L349 | go | train | // Logf logs a formatted string | func (bee *Bee) Logf(format string, args ...interface{}) | // Logf logs a formatted string
func (bee *Bee) Logf(format string, args ...interface{}) | {
s := fmt.Sprintf(format, args...)
log.Printf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 0)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L352-L356 | go | train | // LogErrorf logs a formatted error string | func (bee *Bee) LogErrorf(format string, args ...interface{}) | // LogErrorf logs a formatted error string
func (bee *Bee) LogErrorf(format string, args ...interface{}) | {
s := fmt.Sprintf(format, args...)
log.Errorf("[%s]: %s", bee.Name(), s)
Log(bee.Name(), s, 1)
} |
muesli/beehive | 4bfd4852e0b4bdcbc711323775cc7144ccd81b7e | bees/bees.go | https://github.com/muesli/beehive/blob/4bfd4852e0b4bdcbc711323775cc7144ccd81b7e/bees/bees.go#L359-L366 | go | train | // LogFatal logs a fatal error | func (bee *Bee) LogFatal(args ...interface{}) | // LogFatal logs a fatal error
func (bee *Bee) LogFatal(args ...interface{}) | {
a := []interface{}{"[" + bee.Name() + "]:"}
for _, v := range args {
a = append(a, v)
}
log.Panicln(a...)
Log(bee.Name(), fmt.Sprintln(args...), 2)
} |