dou11655853 2018-08-23 11:07
浏览 391

如何在golang中拆分长struct标签?

Let's say I have following struct where valid is for validation of struct with custom messages for each validator (specially govalidator).

type Login struct {
  Email    string `json:"email" valid:"required~Email is required,email~The email address provided is not valid"`
  Password string `json:"password" valid:"required~Password is required,stringlength(6|40)~Password length must be between 6 and 40"`
}

After adding a few validator, line is too long and not maintainable.

I want to split into new lines but not supported by go and not compatible with reflect.StructTag.Get.

However, according to my testing, validator works with multiline struct tags but vet fails.

Short, what is the correct way to split long struct tags ?

  • 写回答

1条回答 默认 最新

  • duankong8998 2018-08-23 11:17
    关注

    As you noted, the convention expected by StructTag.Get() does not allow using newline characters in struct tags (if you do not follow the convention, StructTag.Get() will not work properly). In my opinion that is just too much stuff being squeezed into a single tag value.

    If you want to store that much meta info about your structures, I would store it outside of struct tags, properly modeled by other structs, so they can be accessed / processed in a type-safe manner.

    If you have no choice and you do need to put that much info into a single tag, then you have to choose between the convenience of using the ready StructTag.Get() method, or omit the convention, use whatever format you want to in the struct tags, and simply implement your own tag-parsing logic.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么