2020-03-19 11:37:31 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package gutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2020-06-17 21:16:25 +08:00
|
|
|
"github.com/gogf/gf/internal/json"
|
2020-03-19 13:38:42 +08:00
|
|
|
"github.com/gogf/gf/util/gconv"
|
2020-03-19 11:37:31 +08:00
|
|
|
"os"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
2020-10-22 09:24:57 +08:00
|
|
|
// apiString is used for type assert api for String().
|
|
|
|
type apiString interface {
|
|
|
|
String() string
|
|
|
|
}
|
|
|
|
|
|
|
|
// apiMapStrAny is the interface support for converting struct parameter to map.
|
|
|
|
type apiMapStrAny interface {
|
|
|
|
MapStrAny() map[string]interface{}
|
|
|
|
}
|
|
|
|
|
2020-03-19 11:37:31 +08:00
|
|
|
// Dump prints variables <i...> to stdout with more manually readable.
|
|
|
|
func Dump(i ...interface{}) {
|
|
|
|
s := Export(i...)
|
|
|
|
if s != "" {
|
|
|
|
fmt.Println(s)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Export returns variables <i...> as a string with more manually readable.
|
|
|
|
func Export(i ...interface{}) string {
|
|
|
|
buffer := bytes.NewBuffer(nil)
|
|
|
|
for _, v := range i {
|
2020-10-22 09:24:57 +08:00
|
|
|
switch r := v.(type) {
|
|
|
|
case []byte:
|
|
|
|
buffer.Write(r)
|
|
|
|
case string:
|
|
|
|
buffer.WriteString(r)
|
|
|
|
default:
|
|
|
|
var (
|
|
|
|
rv = reflect.ValueOf(v)
|
|
|
|
kind = rv.Kind()
|
|
|
|
)
|
2020-03-19 11:37:31 +08:00
|
|
|
if kind == reflect.Ptr {
|
|
|
|
rv = rv.Elem()
|
|
|
|
kind = rv.Kind()
|
|
|
|
}
|
|
|
|
switch kind {
|
|
|
|
case reflect.Slice, reflect.Array:
|
2020-03-19 13:38:42 +08:00
|
|
|
v = gconv.Interfaces(v)
|
2020-10-22 09:24:57 +08:00
|
|
|
case reflect.Map:
|
2020-03-19 13:38:42 +08:00
|
|
|
v = gconv.Map(v)
|
2020-10-22 09:24:57 +08:00
|
|
|
case reflect.Struct:
|
|
|
|
if r, ok := v.(apiMapStrAny); ok {
|
|
|
|
v = r.MapStrAny()
|
|
|
|
} else if r, ok := v.(apiString); ok {
|
|
|
|
v = r.String()
|
|
|
|
}
|
2020-03-19 11:37:31 +08:00
|
|
|
}
|
|
|
|
encoder := json.NewEncoder(buffer)
|
|
|
|
encoder.SetEscapeHTML(false)
|
|
|
|
encoder.SetIndent("", "\t")
|
|
|
|
if err := encoder.Encode(v); err != nil {
|
|
|
|
fmt.Fprintln(os.Stderr, err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return buffer.String()
|
|
|
|
}
|