github.com/gogf/gf/v2@v2.7.4/util/gmeta/gmeta.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gmeta provides embedded meta data feature for struct.
     8  package gmeta
     9  
    10  import (
    11  	"github.com/gogf/gf/v2/container/gvar"
    12  	"github.com/gogf/gf/v2/os/gstructs"
    13  )
    14  
    15  // Meta is used as an embedded attribute for struct to enabled metadata feature.
    16  type Meta struct{}
    17  
    18  const (
    19  	metaAttributeName = "Meta"       // metaAttributeName is the attribute name of metadata in struct.
    20  	metaTypeName      = "gmeta.Meta" // metaTypeName is for type string comparison.
    21  )
    22  
    23  // Data retrieves and returns all metadata from `object`.
    24  func Data(object interface{}) map[string]string {
    25  	reflectType, err := gstructs.StructType(object)
    26  	if err != nil {
    27  		return nil
    28  	}
    29  	if field, ok := reflectType.FieldByName(metaAttributeName); ok {
    30  		if field.Type.String() == metaTypeName {
    31  			return gstructs.ParseTag(string(field.Tag))
    32  		}
    33  	}
    34  	return map[string]string{}
    35  }
    36  
    37  // Get retrieves and returns specified metadata by `key` from `object`.
    38  func Get(object interface{}, key string) *gvar.Var {
    39  	v, ok := Data(object)[key]
    40  	if !ok {
    41  		return nil
    42  	}
    43  	return gvar.New(v)
    44  }