github.com/gogf/gf@v1.16.9/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/container/gvar"
    12  	"github.com/gogf/gf/internal/structs"
    13  )
    14  
    15  // Meta is used as an embedded attribute for struct to enabled meta data feature.
    16  type Meta struct{}
    17  
    18  const (
    19  	// metaAttributeName is the attribute name of meta data in struct.
    20  	metaAttributeName = "Meta"
    21  )
    22  
    23  // Data retrieves and returns all metadata from `object`.
    24  // It automatically parses and caches the tag string from "Mata" attribute as its meta data.
    25  func Data(object interface{}) map[string]interface{} {
    26  	reflectType, err := structs.StructType(object)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	if field, ok := reflectType.FieldByName(metaAttributeName); ok {
    31  		var (
    32  			tags = structs.ParseTag(string(field.Tag))
    33  			data = make(map[string]interface{}, len(tags))
    34  		)
    35  		for k, v := range tags {
    36  			data[k] = v
    37  		}
    38  		return data
    39  	}
    40  	return map[string]interface{}{}
    41  }
    42  
    43  // Get retrieves and returns specified metadata by `key` from `object`.
    44  func Get(object interface{}, key string) *gvar.Var {
    45  	return gvar.New(Data(object)[key])
    46  }