Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split long struct tags in golang?

Tags:

string

struct

go

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 ?

like image 889
ferhat Avatar asked Aug 23 '18 11:08

ferhat


People also ask

Can you have multiple tag strings in struct field in Go?

This meta-data is declared using a string literal in the format key:"value" and are separated by space. That is, you can have multiple tags in the same field, serving different purposes and libraries.

What is tag Golang?

In Golang, we use Tags as metadata to provide for each field in a struct. This information is made available using reflection. This is typically used by packages that transform data from one form to another. For example, we can use Tags to encode/decode JSON data or read and write from a DB.

How do you use struct tags?

To use struct tags to accomplish something, other Go code must be written to examine structs at runtime. The standard library has packages that use struct tags as part of their operation. The most popular of these is the encoding/json package.

How do Go tags work?

Tags are a way to attach additional information to a struct field. A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag.


1 Answers

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.

like image 191
icza Avatar answered Oct 06 '22 01:10

icza