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 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web