gf/util/gmeta/gmeta.go

51 lines
1.4 KiB
Go
Raw Normal View History

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gmeta provides embedded meta data feature for struct.
package gmeta
import (
"github.com/gogf/gf/container/gvar"
"github.com/gogf/gf/internal/structs"
)
2021-10-06 20:11:54 +08:00
// Meta is used as an embedded attribute for struct to enabled metadata feature.
type Meta struct{}
const (
2021-10-06 20:11:54 +08:00
// metaAttributeName is the attribute name of metadata in struct.
metaAttributeName = "Meta"
)
2021-08-27 20:16:29 +08:00
// Data retrieves and returns all metadata from `object`.
2021-10-06 20:11:54 +08:00
// It automatically parses and caches the tag string from "Mata" attribute as its metadata.
func Data(object interface{}) map[string]interface{} {
reflectType, err := structs.StructType(object)
if err != nil {
panic(err)
}
2021-08-27 20:16:29 +08:00
if field, ok := reflectType.FieldByName(metaAttributeName); ok {
var (
tags = structs.ParseTag(string(field.Tag))
data = make(map[string]interface{}, len(tags))
)
for k, v := range tags {
data[k] = v
}
2021-08-27 20:16:29 +08:00
return data
}
return map[string]interface{}{}
}
2021-08-27 20:16:29 +08:00
// Get retrieves and returns specified metadata by `key` from `object`.
func Get(object interface{}, key string) *gvar.Var {
2021-10-06 20:11:54 +08:00
v := Data(object)[key]
if v == nil {
return nil
}
return gvar.New(v)
}