Repository navigation
Expand file tree
/
Copy pathgutil.go
More file actions
84 lines (77 loc) · 2.31 KB
/
Copy pathgutil.go
File metadata and controls
84 lines (77 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2017 gf Author(https://gitee.com/johng/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://gitee.com/johng/gf.
// 其他工具包
package gutil
import (
"fmt"
"bytes"
"encoding/json"
"reflect"
"gitee.com/johng/gf/g/util/gconv"
"runtime"
"gitee.com/johng/gf/g/os/glog"
)
// 格式化打印变量(类似于PHP-vardump)
func Dump(i...interface{}) {
for _, v := range i {
if b, ok := v.([]byte); ok {
fmt.Print(string(b))
} else {
// 主要针对 map[interface{}]* 进行处理,json无法进行encode,
// 这里强制对所有map进行反射处理转换
refValue := reflect.ValueOf(v)
if refValue.Kind() == reflect.Map {
m := make(map[string]interface{})
keys := refValue.MapKeys()
for _, k := range keys {
key := gconv.String(k.Interface())
m[key] = refValue.MapIndex(k).Interface()
}
v = m
}
// json encode并打印到终端
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", "\t")
if err := encoder.Encode(v); err == nil {
fmt.Print(buffer.String())
} else {
fmt.Errorf("%s", err.Error())
}
}
//fmt.Println()
}
}
// 打印完整的调用回溯信息
func PrintBacktrace() {
index := 1
buffer := bytes.NewBuffer(nil)
for i := 0; i < 10000; i++ {
if _, cfile, cline, ok := runtime.Caller(i); ok {
buffer.WriteString(fmt.Sprintf(`%d. %s:%d%s`, index, cfile, cline, "\n"))
index++
} else {
break
}
}
glog.Header(false).Print(buffer.String())
}
// 抛出一个异常
func Throw(exception interface{}) {
panic(exception)
}
// try...catch...
func TryCatch(try func(), catch ... func(exception interface{})) {
if len(catch) > 0 {
defer func() {
if e := recover(); e != nil {
catch[0](e)
}
}()
}
try()
}