Use of structure tags in go language

Tags in go are used in structures. Has two functions:

(1) Give structure attributes aliases and field mapping. Different types correspond to different values, such as xml, yaml, json, etc., which correspond to different areas. Of course, the labels are also different. For example, json and bson are all conventional.

(2) Make attribute judgment and verification.

Format in 1.tag

(1) The tag itself is a string, and the entire string uses backticks “.

(2) The key must be a non-empty string and cannot use double quotes. The string cannot contain control characters, spaces, quotes, or colons.

(3) value is a string marked with double quotes.

(4) Use spaces to connect multiple tags. The tag name does not need to use double quotes. The value corresponding to the tag name needs to use double quotes. Multiple tag values need to use commas to connect.

Example:

type User struct {
UserId int `json:"user_id" bson:"b_user_id,bson_id"`
UserName string `json:"user_name" bson:"b_user_name"`
}

Note: There cannot be spaces before or after the colon.

For example the following are conventional tags: bson, json, yaml, xml, etc. Of course, this tag can be customized

2.json, bson tag

type User struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Username string `json:"username,omitempty" bson:"username,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
} 

For example, in the above code, labels are used to create aliases, but each label has a different role. For example, json is often used when interacting with the front and back ends. For example, requests and responses are all in json format. bson is mostly used when interacting with mongoDB database.

json tag: The json tag is used to specify the name and behavior of the field in json encoding. When interacting with the front-end data, using the json tag can ensure that the field has Correct name and behavior.

bson tag: The bson tag is used. The bson tag is used to specify the name and behavior of the field in the MongoDB database. When using the MongoDB database for data storage, using the bson tag ensures that fields have correct names and behavior when serializing and deserializing BSON (Binary JSON) data.

By aliasing fields with these tags, field mapping can be established on the front end and database side to ensure the correct transmission and storage of data.

1. JSON tag (json):
   - Use the json:"field_name" tag on a structure field to specify aliases and options for the field in JSON encoding and decoding.
   - For example: UserName string json:"user_name"
   - Such a tag can specify the use of "user_name" as an alias for a field in JSON encoding and decoding.
 
2. BSON tag (bson):
   - Use the bson:"field_name" tag on a structure field to specify aliases and options for the field in BSON encoding and decoding.
   - For example: UserName string bson:"b_user_name"
   - Such a tag can specify the use of "b_user_name" as an alias for a field in BSON encoding and decoding.
 
3. YAML tag (yaml):
   - Use the yaml:"field_name" tag on a structure field to specify aliases and options for the field in YAML encoding and decoding.
   - For example: UserName string yaml:"user_name"
   - Such a tag can specify the use of "user_name" as an alias for a field in YAML encoding and decoding.
 
4. XML tag (xml):
   - Use the xml:"field_name" tag on a structure field to specify aliases and options for the field in XML encoding and decoding.
   - For example: UserName string xml:"user_name"
   - Such a tag can specify the use of "user_name" as an alias for a field in XML encoding and decoding.
 
It is important to note that the specific meaning of these tags and how they are used may vary depending on the library or tool used. These examples show the general usage of different tags in the Go language, but the specific implementation may vary depending on the library or tool.
 
As for reading YAML and XML files, you can use the corresponding libraries for parsing and processing. For YAML files, you can use the gopkg.in/yaml.v2 package. For XML files, you can use the encoding/xml package or other third-party packages for parsing and processing. 

3. Example

In fact, you can also think of examples yourself, and the following cases are for reference.

type Student struct {
// When returning to the front end, the first letter is capitalized, which is weird, so I gave Name an alias.
Name string `json:"name"`
Age int
}

func testTag() {
s1 := Student{
Name: "s1k",
}
bytes, err := json.Marshal(s1)
if err != nil {
panic(err)
}
//Convert []byte array to string type json type
//s := string(bytes)
varsStudent
json.Unmarshal(bytes, &s)
fmt.Printf("%v", s)
}

typeUser struct {
UserId int `json:"user_id" bson:"b_user_id"`
UserName string `json:"user_name" bson:"b_user_name"`
}

func testJson() {
u := & amp;User{
UserId: 1,
UserName: "tony",
}

fmt.Printf("%T", u)
bytes, _ := json.Marshal(u)

fmt.Println(string(bytes))

// Get the value of the tag through reflection
// reflect.TypeOf(u), what is obtained is the pointer type
types := reflect.TypeOf(u)

field := types.Elem().Field(0)
fmt.Println(field.Tag.Get("json"))
fmt.Println(field.Tag.Get("bson"))
}

type Http struct {
Port string `yaml:"port"`
Secret string `yaml:"secretKey"`
Domain string `yaml:"domain"`
}

type Config struct {
Http `yaml:"http"`
}

func testYaml() {
//var h Http
config := new(Config)
file, err := ioutil.ReadFile("config.yaml")
if err != nil {
fmt.Println(err.Error())
}
// Store the parsed data into the structure
err = yaml.Unmarshal(file, config)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(config.Http, " ", config.Port, " ", config.Secret, " ", config.Domain)
}

type Person struct {
Name string `json:"name"`
Age string `json:"age,omitempty"` //There is omitempty attribute, so when encoding/json converts the object into a json string,
// As long as Addr in the object is found to be false, 0, null pointer, null interface, empty array, null slice, null map, or empty string, it will be ignored.
}

func testTags() {
p1 := &Person{
Name: "zhangsan",
}
// So empty strings will be ignored
bytes, _ := json.Marshal(p1)
fmt.Printf("%s", bytes)
fmt.Println(p1)
fmt.Printf("%T", p1)

p2 := &Person{
Name: "lisi",
Age: "15",
}
fmt.Println(p2)
}

// Remove the tag from the structure through reflection
/*
Get field field
Get tag tag
Get the key-value pair key:value

// Three ways to get field
field := reflect.TypeOf(obj).FieldByName("Name")
field := reflect.ValueOf(obj).Type().Field(i) // i represents the field number
field := reflect.ValueOf( & amp;obj).Elem().Type().Field(i) // i represents the field number

// Get Tag
tag := field.Tag

// Get key-value pairs
labelValue := tag.Get("label")
labelValue,ok := tag.Lookup("label")
*/
func getTag() {
p2 := &Person{
Name: "lisi",
Age: "15",
}
//Three ways to get Field
field := reflect.ValueOf(p2).Elem().Type().Field(1)
getName := field.Tag.Get("json")
// Get tag

//value, ok := tag.Lookup("name")
fmt.Println(getName)
}