Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. package common
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. // `flatten` recursively retrieves every leaf node in a struct in depth-first fashion
  9. // and aggregate the results into given string slice with format: "path.to.leaf = value"
  10. // in the order of definition. Root name is ignored in the path. This helper function is
  11. // useful to pretty-print a struct, such as configs.
  12. // for example, given data structure:
  13. // A{
  14. // B{
  15. // C: "foo",
  16. // D: 42,
  17. // },
  18. // E: nil,
  19. // }
  20. // it should yield a slice of string containing following items:
  21. // [
  22. // "B.C = \"foo\"",
  23. // "B.D = 42",
  24. // "E =",
  25. // ]
  26. func Flatten(i interface{}) []string {
  27. var res []string
  28. flatten("", &res, reflect.ValueOf(i))
  29. return res
  30. }
  31.  
  32. const DELIMITER = "."
  33.  
  34. func flatten(k string, m *[]string, v reflect.Value) {
  35. delimiter := DELIMITER
  36. if k == "" {
  37. delimiter = ""
  38. }
  39.  
  40. switch v.Kind() {
  41. case reflect.Ptr:
  42. if v.IsNil() {
  43. *m = append(*m, fmt.Sprintf("%s =", k))
  44. return
  45. }
  46. flatten(k, m, v.Elem())
  47. case reflect.Struct:
  48. if x, ok := v.Interface().(fmt.Stringer); ok {
  49. *m = append(*m, fmt.Sprintf("%s = %v", k, x))
  50. return
  51. }
  52.  
  53. for i := 0; i < v.NumField(); i++ {
  54. flatten(k+delimiter+v.Type().Field(i).Name, m, v.Field(i))
  55. }
  56. case reflect.String:
  57. // It is useful to quote string values
  58. *m = append(*m, fmt.Sprintf("%s = \"%s\"", k, v))
  59. default:
  60. *m = append(*m, fmt.Sprintf("%s = %v", k, v))
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement