2021-02-07 21:23:09 +08:00
|
|
|
// 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 (
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/container/gvar"
|
2021-11-24 16:17:50 +08:00
|
|
|
"github.com/gogf/gf/v2/os/gstructs"
|
2021-02-07 21:23:09 +08:00
|
|
|
)
|
|
|
|
|
2021-10-06 20:11:54 +08:00
|
|
|
// Meta is used as an embedded attribute for struct to enabled metadata feature.
|
2021-02-07 21:23:09 +08:00
|
|
|
type Meta struct{}
|
|
|
|
|
|
|
|
const (
|
2022-05-18 17:57:16 +08:00
|
|
|
metaAttributeName = "Meta" // metaAttributeName is the attribute name of metadata in struct.
|
|
|
|
metaTypeName = "gmeta.Meta" // metaTypeName is for type string comparison.
|
2021-02-07 21:23:09 +08:00
|
|
|
)
|
|
|
|
|
2021-08-27 20:16:29 +08:00
|
|
|
// Data retrieves and returns all metadata from `object`.
|
2021-10-21 20:17:02 +08:00
|
|
|
func Data(object interface{}) map[string]string {
|
2021-11-24 16:17:50 +08:00
|
|
|
reflectType, err := gstructs.StructType(object)
|
2021-02-07 21:23:09 +08:00
|
|
|
if err != nil {
|
2021-10-25 21:06:24 +08:00
|
|
|
return nil
|
2021-02-07 21:23:09 +08:00
|
|
|
}
|
2021-08-27 20:16:29 +08:00
|
|
|
if field, ok := reflectType.FieldByName(metaAttributeName); ok {
|
2022-05-18 17:57:16 +08:00
|
|
|
if field.Type.String() == metaTypeName {
|
|
|
|
return gstructs.ParseTag(string(field.Tag))
|
|
|
|
}
|
2021-08-27 20:16:29 +08:00
|
|
|
}
|
2021-10-21 20:17:02 +08:00
|
|
|
return map[string]string{}
|
2021-02-07 21:23:09 +08:00
|
|
|
}
|
|
|
|
|
2021-08-27 20:16:29 +08:00
|
|
|
// Get retrieves and returns specified metadata by `key` from `object`.
|
2021-02-07 21:23:09 +08:00
|
|
|
func Get(object interface{}, key string) *gvar.Var {
|
2021-10-21 20:17:02 +08:00
|
|
|
v, ok := Data(object)[key]
|
|
|
|
if !ok {
|
2021-10-06 20:11:54 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return gvar.New(v)
|
2021-02-07 21:23:09 +08:00
|
|
|
}
|