gutil_dump.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 gutil
  7. import (
  8. "bytes"
  9. "fmt"
  10. "github.com/gogf/gf/internal/json"
  11. "github.com/gogf/gf/util/gconv"
  12. "os"
  13. "reflect"
  14. )
  15. // apiVal is used for type assert api for Val().
  16. type apiVal interface {
  17. Val() interface{}
  18. }
  19. // apiString is used for type assert api for String().
  20. type apiString interface {
  21. String() string
  22. }
  23. // apiMapStrAny is the interface support for converting struct parameter to map.
  24. type apiMapStrAny interface {
  25. MapStrAny() map[string]interface{}
  26. }
  27. // Dump prints variables <i...> to stdout with more manually readable.
  28. func Dump(i ...interface{}) {
  29. s := Export(i...)
  30. if s != "" {
  31. fmt.Println(s)
  32. }
  33. }
  34. // Export returns variables <i...> as a string with more manually readable.
  35. func Export(i ...interface{}) string {
  36. buffer := bytes.NewBuffer(nil)
  37. for _, value := range i {
  38. switch r := value.(type) {
  39. case []byte:
  40. buffer.Write(r)
  41. case string:
  42. buffer.WriteString(r)
  43. default:
  44. var (
  45. reflectValue = reflect.ValueOf(value)
  46. reflectKind = reflectValue.Kind()
  47. )
  48. for reflectKind == reflect.Ptr {
  49. reflectValue = reflectValue.Elem()
  50. reflectKind = reflectValue.Kind()
  51. }
  52. switch reflectKind {
  53. case reflect.Slice, reflect.Array:
  54. value = gconv.Interfaces(value)
  55. case reflect.Map:
  56. value = gconv.Map(value)
  57. case reflect.Struct:
  58. converted := false
  59. if r, ok := value.(apiVal); ok {
  60. if result := r.Val(); result != nil {
  61. value = result
  62. converted = true
  63. }
  64. }
  65. if !converted {
  66. if r, ok := value.(apiMapStrAny); ok {
  67. if result := r.MapStrAny(); result != nil {
  68. value = result
  69. converted = true
  70. }
  71. }
  72. }
  73. if !converted {
  74. if r, ok := value.(apiString); ok {
  75. value = r.String()
  76. }
  77. }
  78. }
  79. encoder := json.NewEncoder(buffer)
  80. encoder.SetEscapeHTML(false)
  81. encoder.SetIndent("", "\t")
  82. if err := encoder.Encode(value); err != nil {
  83. fmt.Fprintln(os.Stderr, err.Error())
  84. }
  85. }
  86. }
  87. return buffer.String()
  88. }