printStruct.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2013-2014 Fuzamei tech Ltd. All rights reserved.
  2. package gocctp
  3. import "reflect"
  4. import "fmt"
  5. type structItem struct {
  6. Offset int
  7. Align int
  8. Size int
  9. Name string
  10. Value interface{}
  11. }
  12. func structKV(i interface{}, recursion bool) ([]structItem, error) {
  13. values := reflect.ValueOf(i)
  14. if values.Kind() == reflect.Ptr {
  15. return structKV(values.Elem().Interface(), recursion)
  16. }
  17. if values.Kind() != reflect.Struct {
  18. return nil, fmt.Errorf("StructKeyValues: in params not a struct")
  19. }
  20. types := reflect.TypeOf(i)
  21. num := types.NumField()
  22. elms := make([]structItem, 0)
  23. for i := 0; i < num; i++ {
  24. elm := values.Field(i)
  25. fmt.Println(elm.CanInterface())
  26. if elm.CanInterface() {
  27. if recursion && elm.Kind() == reflect.Struct {
  28. v, err := structKV(elm.Interface(), recursion)
  29. if err == nil && len(v) > 0 {
  30. elms = append(elms, v...)
  31. }
  32. continue
  33. }
  34. field := types.Field(i)
  35. item := structItem{}
  36. item.Offset = int(field.Offset)
  37. item.Align = int(field.Type.Align())
  38. item.Size = int(field.Type.Size())
  39. item.Name = field.Name
  40. item.Value = elm.Interface()
  41. elms = append(elms, item)
  42. }
  43. }
  44. return elms, nil
  45. }
  46. func PrintStruct(item interface{}) {
  47. data, err := structKV(item, true)
  48. if err != nil {
  49. panic(err)
  50. }
  51. types := reflect.TypeOf(item)
  52. fmt.Println("name:", types.Name(), "total:", types.Size())
  53. for i := 0; i < len(data); i++ {
  54. fmt.Println(data[i])
  55. }
  56. }