Introduction

Mainly used for embedding into user-defined structs, and through the form of tags to attach custom tag content (metadata) to the struct of the gmeta package, and dynamically retrieve these custom tag contents at runtime through specific methods.

Usage:

  1. import "github.com/gogf/gf/v2/util/gmeta"

API Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/util/gmeta

Method List:

  1. func Data(object interface{}) map[string]interface{}
  2. func Get(object interface{}, key string) *gvar.Var

Usage Example

Data Method

The Data method is used to obtain the metadata tags of a specified struct object and return them as a map.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/util/gmeta"
  6. )
  7. func main() {
  8. type User struct {
  9. g.Meta `orm:"user" db:"mysql"`
  10. Id int
  11. Name string
  12. }
  13. g.Dump(gmeta.Data(User{}))
  14. }

Metadata - 图1tip

Most of the time, in struct definitions, we use the alias g.Meta for gmeta.Meta.

After execution, the terminal outputs:

  1. {
  2. "db": "mysql",
  3. "orm": "user"
  4. }

Get Method

The Get method is used to retrieve metadata tag information of a specified name from a specified struct object.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/util/gmeta"
  5. )
  6. func main() {
  7. type User struct {
  8. g.Meta `orm:"user" db:"mysql"`
  9. Id int
  10. Name string
  11. }
  12. user := User{}
  13. fmt.Println(gmeta.Get(user, "orm").String())
  14. fmt.Println(gmeta.Get(user, "db").String())
  15. }

After execution, the terminal outputs:

  1. user
  2. mysql