gmeta.go 1.3 KB

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