gmeta.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // Package gmeta provides embedded meta data feature for struct.
  7. package gmeta
  8. import (
  9. "github.com/gogf/gf/v2/container/gvar"
  10. "github.com/gogf/gf/v2/os/gstructs"
  11. )
  12. // Meta is used as an embedded attribute for struct to enabled metadata feature.
  13. type Meta struct{}
  14. const (
  15. metaAttributeName = "Meta" // metaAttributeName is the attribute name of metadata in struct.
  16. metaTypeName = "gmeta.Meta" // metaTypeName is for type string comparison.
  17. )
  18. // Data retrieves and returns all metadata from `object`.
  19. func Data(object interface{}) map[string]string {
  20. reflectType, err := gstructs.StructType(object)
  21. if err != nil {
  22. return nil
  23. }
  24. if field, ok := reflectType.FieldByName(metaAttributeName); ok {
  25. if field.Type.String() == metaTypeName {
  26. return gstructs.ParseTag(string(field.Tag))
  27. }
  28. }
  29. return map[string]string{}
  30. }
  31. // Get retrieves and returns specified metadata by `key` from `object`.
  32. func Get(object interface{}, key string) *gvar.Var {
  33. v, ok := Data(object)[key]
  34. if !ok {
  35. return nil
  36. }
  37. return gvar.New(v)
  38. }