结合使用GO GIN-GONIC、GORM和VALIDATOR.V2。

huangapple go评论77阅读模式
英文:

combining GO GIN-GONIC GORM and VALIDATOR.V2

问题

我对Go还不太熟悉,但我可以帮你翻译你提供的内容。以下是翻译的结果:

我对Go还不太熟悉,我想通过设置一个GIN-GONIC API来开始。我找到了这个教程,我对那个框架非常满意。但是现在我在验证过程中遇到了问题,我添加了"gopkg.in/validator.v2"和

type Todo struct {
    gorm.Model
    Title     string `json:"title" **validate:"size:2"**`
    Completed int `json:"completed"`
}

变成了

type Todo struct {
    gorm.Model
    Title     string `json:"title" **validate:"size:2"**`
    Completed int `json:"completed"`
}

然后在我添加的CreateTodo函数中:

if errs := validator.Validate(todo); errs!=nil {
    c.JSON(500, gin.H{"Error": errs.Error()})
}

但是当我发送一个POST请求时,会返回以下错误信息:

> "Error": "Type: unknown tag"

经过一些研究,我发现:

> 在字段标签中使用一个不存在的验证函数将始终返回false,并带有错误validate.ErrUnknownTag

所以**validate:"size:2"**可能是错误的...

我不明白如何设置验证,也不知道如何在"catch"中显示正确的错误信息:

c.JSON(500, gin.H{"Error": errs.Error()})
英文:

I am quite new to Go and I would like to startup by setting a GIN-GONIC API. I found this tutorial and I am very happy with that skeleton. But now I am stuck with the validating process which I added: "gopkg.in/validator.v2" and

type Todo struct {
    gorm.Model
	Title     string `json:"title"`
    Completed int `json:"completed"`
}

became

type Todo struct {
    gorm.Model
	Title     string `json:"title" **validate:"size:2"**`
    Completed int `json:"completed"`
}

and then in the CreateTodo function which I added :

if errs := validator.Validate(todo); errs!=nil {
	c.JSON(500, gin.H{"Error": errs.Error()})
}

but then a POST call send :

> "Error": "Type: unknown tag"

after some research I found that :
> Using a non-existing validation func in a field tag will always return false and with error validate.ErrUnknownTag.

so the **validate:"size:2"** must be wrong ...

I don't get how to set the validation and also how to display the correct error within the "catch":

c.JSON(500, gin.H{"Error": errs.Error()})

答案1

得分: 0

看起来你还没有定义size验证函数。你可以这样做。

自定义验证函数

func size(v interface{}, param int) error {
    st := reflect.ValueOf(v)
    if st.Kind() != reflect.String {
        return validate.ErrUnsupported
    }

    if utf8.RuneCountInString(st.String()) != param {
        return errors.New("Wrong size")
    }
    return nil
}

validate.SetValidationFunc("size", size)
英文:

Looks like you haven't defined size validation function. Also you can do it.

Custom validation functions:

func size(v interface{}, param int) error {
    st := reflect.ValueOf(v)
	if st.Kind() != reflect.String {
    	return validate.ErrUnsupported
	}

    if utf8.RuneCountInString(st.String()) != param {
	    return errors.New("Wrong size")
	}
    return nil
}

validate.SetValidationFunc("size", size)

huangapple
  • 本文由 发表于 2017年2月10日 17:26:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/42155776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定