Details on how golang USES the tag attributes of struct

  • 2020-06-23 00:36:16
  • OfStack

Let's start with an example

We often come across struct definitions in the following format:


type Person struct {
  Name string `json:"name"`
  Age int  `json:"age"`
}

This struct defines a type called Person and contains two fields, Name and Age; But behind the domain is the magic json:"name". What does this do? This article tries to explain the problem.

This feature is often used when golang objects need to be converted to json.

There are two caveats:

1. If a field does not begin with a capital letter, it will be ignored when converted to json.


$ cat main.go
package main

import (
  "fmt"
  "encoding/json"
)

type Person struct {
  Name string `json:"name"`
  age int  `json:"age"`
}

func main() {
  person := Person { "tom", 12 }
  if b, err := json.Marshal(person); err != nil {
    fmt.Printf("error: %s", err.Error())
  } else {
    fmt.Printf("value: %s", b)
  }
}
$ go build -o main main.go 
$ ./main
value: {"name":"tom"}

We see that after converting to the json string, name outputs normally, while age is discarded because age begins with a lowercase letter.

2. If json:"name" tag is not used, the output json field name and domain name are the same.


$ cat main.go
package main

import (
  "fmt"
  "encoding/json"
)

type Person struct {
  Name string
  Age int
}

func main() {
  person := Person { "tom", 12 }
  if b, err := json.Marshal(person); err != nil {
    fmt.Printf("error: %s", err.Error())
  } else {
    fmt.Printf("value: %s", b)
  }
}
$ go build -o main main.go 
$ ./main
value: {"Name":"tom","Age":12}

We see that the output json string USES the field name defined by struct.

In summary 1, the json:"name" format string is used to guide json.Marshal /Unmarshal to map field names when converting between json strings and golang objects. For another example, json strings and golang domain names can be converted arbitrarily:


$ cat main.go

package main

import (
  "fmt"
  "encoding/json"
)

type Person struct {
  Name string  `json:"age"`
  Age int    `json:"address"`
}

func main() {
  person := Person { "tom", 12 }
  if b, err := json.Marshal(person); err != nil {
    fmt.Printf("error: %s", err.Error())
  } else {
    fmt.Printf("value: %s", b)
  }
}
$ go build -o main main.go 
$ ./main
value: {"age":"tom","address":12}

In this example we map Name to age and Age to address, which of course is a weird mapping, there is no positive meaning, only negative meaning, just to show that you can map any name.

If we go to see a json package source code, I can see in the encoding/json/encode go, encoding/json/decode go there read tag worth relevant code.


tag := sf.Tag.Get("json")

This means that the tag of json is used by json. Marshal and json. Unmarshal.

How do we use tag

Again, Person has a field, Age. Can we limit the value of Age to between 1 and 100? It's not too big, otherwise it's meaningless.


$ cat main.go
package main

import (
  "fmt"
  "strings"
  "strconv"
  "reflect"
 _ "encoding/json"
)

type Person struct {
  Name string  `json:"name"`
  Age int    `json:"age" valid:"1-100"`
}

func (p * Person) validation() bool {
  v := reflect.ValueOf(*p)
  tag := v.Type().Field(1).Tag.Get("valid")
  val := v.Field(1).Interface().(int)
  fmt.Printf("tag=%v, val=%v\n", tag, val)
  
  result := strings.Split(tag, "-")
  var min, max int
  min, _ = strconv.Atoi(result[0])
  max, _ = strconv.Atoi(result[1])

  if val >= min && val <= max {
    return true
  } else {
    return false
  }
}

func main() {
  person1 := Person { "tom", 12 }
  if person1.validation() {
    fmt.Printf("person 1: valid\n")
  } else {
    fmt.Printf("person 1: invalid\n")
  }
  person2 := Person { "tom", 250 }
  if person2.validation() {
    fmt.Printf("person 2 valid\n")
  } else {
    fmt.Printf("person 2 invalid\n")
  }
}

In this example, we add an validate function to Person, and validate verifies that age is reasonable.

This function extends validation against any valid field of any struct.


$ cat main.go
package main

import (
  "fmt"
  "strings"
  "strconv"
  "reflect"
 _ "encoding/json"
)

type Person struct {
  Name string  `json:"name"`
  Age int    `json:"age" valid:"1-100"`
}

type OtherStruct struct {
  Age int    `valid:"20-300"`
}

func validateStruct(s interface{}) bool {
 v := reflect.ValueOf(s)

 for i := 0; i < v.NumField(); i++ {
  fieldTag  := v.Type().Field(i).Tag.Get("valid")
  fieldName  := v.Type().Field(i).Name
  fieldType  := v.Field(i).Type()
  fieldValue := v.Field(i).Interface()

  if fieldTag == "" || fieldTag == "-" {
    continue
  }

  if fieldName == "Age" && fieldType.String() == "int" {
    val := fieldValue.(int)

    tmp := strings.Split(fieldTag, "-")
    var min, max int
    min, _ = strconv.Atoi(tmp[0])
    max, _ = strconv.Atoi(tmp[1])
    if val >= min && val <= max {
      return true
    } else {
      return false
    }
  }
 }
 return true
}

func main() {
  person1 := Person { "tom", 12 }
  if validateStruct(person1) {
    fmt.Printf("person 1: valid\n")
  } else {
    fmt.Printf("person 1: invalid\n")
  }

  person2 := Person { "jerry", 250 }
  if validateStruct(person2) {
    fmt.Printf("person 2: valid\n")
  } else {
    fmt.Printf("person 2: invalid\n")
  }

  other1 := OtherStruct { 12 }
  if validateStruct(other1) {
    fmt.Printf("other 1: valid\n")
  } else {
    fmt.Printf("other 1: invalid\n")
  }

  other2 := OtherStruct { 250 }
  if validateStruct(other2) {
    fmt.Printf("other 2: valid\n")
  } else {
    fmt.Printf("other 2: invalid\n")
  }
}

In this example, we define a function validateStruct that takes any one struct as an argument. validateStruct validates all Age fields defined in struct. If the field name is Age, the field type is int, and valid tag is defined, then the valid is validated.

See the execution results:

[

$ go build -o main main.go
$ ./main
person 1: valid
person 2: invalid
other 1: invalid
other 2: valid

]

Related articles: