structs_map.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). 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 structs
  7. // MapField retrieves struct field as map[name/tag]*Field from <pointer>, and returns the map.
  8. //
  9. // The parameter <pointer> should be type of struct/*struct.
  10. //
  11. // The parameter <priority> specifies the priority tag array for retrieving from high to low.
  12. //
  13. // Note that it only retrieves the exported attributes with first letter up-case from struct.
  14. func MapField(pointer interface{}, priority []string) (map[string]*Field, error) {
  15. fields, err := getFieldValues(pointer)
  16. if err != nil {
  17. return nil, err
  18. }
  19. var (
  20. tagValue = ""
  21. mapField = make(map[string]*Field)
  22. )
  23. for _, field := range fields {
  24. // Only retrieve exported attributes.
  25. if !field.IsExported() {
  26. continue
  27. }
  28. tagValue = ""
  29. for _, p := range priority {
  30. tagValue = field.Tag(p)
  31. if tagValue != "" && tagValue != "-" {
  32. break
  33. }
  34. }
  35. tempField := field
  36. tempField.TagValue = tagValue
  37. if tagValue != "" {
  38. mapField[tagValue] = tempField
  39. } else {
  40. if field.IsEmbedded() {
  41. m, err := MapField(field.value, priority)
  42. if err != nil {
  43. return nil, err
  44. }
  45. for k, v := range m {
  46. if _, ok := mapField[k]; !ok {
  47. tempV := v
  48. mapField[k] = tempV
  49. }
  50. }
  51. } else {
  52. mapField[field.Name()] = tempField
  53. }
  54. }
  55. }
  56. return mapField, nil
  57. }