get.go 996 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package objutils
  2. import "fmt"
  3. type NestedFieldNotFoundError struct {
  4. Field string
  5. }
  6. func (e *NestedFieldNotFoundError) Error() string {
  7. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  8. }
  9. // GetNestedString finds a nested string in a set of map objects. Arrays not supported.
  10. func GetNestedString(obj map[string]interface{}, fields ...string) (string, error) {
  11. curr := obj
  12. lastIndex := len(fields) - 1
  13. for _, field := range fields[0:lastIndex] {
  14. objField, ok := curr[field]
  15. if !ok {
  16. return "", &NestedFieldNotFoundError{field}
  17. }
  18. curr, ok = objField.(map[string]interface{})
  19. if !ok {
  20. return "", fmt.Errorf("%s is not a nested object", field)
  21. }
  22. }
  23. // convert the last field to a string
  24. strFieldGeneric, ok := curr[fields[lastIndex]]
  25. if !ok {
  26. return "", &NestedFieldNotFoundError{fields[lastIndex]}
  27. }
  28. res, ok := strFieldGeneric.(string)
  29. if !ok {
  30. return "", fmt.Errorf("%s is not a string", fields[lastIndex])
  31. }
  32. return res, nil
  33. }