去游乐场url验证



我正在发送一个请求,它在正文中有一个URL and Content。验证是这样的,URL或震中是强制性的。当URL为空时,程序出错,因为空字符串上的url validate失败。

是否有一种方法可以在url上运行url验证,如果它不是空的?

这是我的代码片段。

func (d *Doc) UnmarshalJSON(bytearray []byte) error {
type doc struct {
ID           ID      `json:"id" validate:"omitempty,numeric"`
URL          string  `json:"url" validate:"required_without=Content,url"`
Content      string  `json:"content" validate:"required_without=Url"`

}
var d doc
if err := json.Unmarshal(bytearray, &d); err != nil {
return err
}
}

在repo中有一个类似的问题,建议使用结构级验证。

验证器示例中的示例用法:https://github.com/go-playground/validator/blob/v9/_examples/struct-level/main.go#L48

下面的代码没有经过测试,但是可以作为一个很好的起点:

import (
"json"
"gopkg.in/go-playground/validator.v9"
)
func init() {
validate.RegisterStructValidation(DocStructLevelValidation, doc{})
}
type doc struct {
ID           ID      `json:"id" validate:"omitempty,numeric"`
URL          string  `json:"url"`
Content      string  `json:"content"`
}
func DocStructLevelValidation(sl validator.StructLevel) {
d := sl.Current().Interface().(doc)
if d.URL == "" && d.Content == "" {
sl.ReportError(d.URL, "url", "URL", "urlcontentrequired", "")
sl.ReportError(d.Content, "content", "Content", "urlcontentrequired", "")
}
}
func (d *Doc) UnmarshalJSON(bytearray []byte) error {
var d doc
if err := json.Unmarshal(bytearray, &d); err != nil {
return err
}
}

最新更新