forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goutil.go
112 lines (97 loc) · 2.43 KB
/
goutil.go
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Package goutil Useful utils for the Go: int, string, array/slice, map, format, cli, env, filesystem, testing and more.
package goutil
import (
"fmt"
"reflect"
"runtime"
"strings"
)
// FuncName get func name
func FuncName(f interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// PkgName get current package name
// Usage:
// funcName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
// pgkName := goutil.PkgName(funcName)
func PkgName(funcName string) string {
for {
lastPeriod := strings.LastIndex(funcName, ".")
lastSlash := strings.LastIndex(funcName, "/")
if lastPeriod > lastSlash {
funcName = funcName[:lastPeriod]
} else {
break
}
}
return funcName
}
// GetCallStacks stacks is a wrapper for runtime.
// Stack that attempts to recover the data for all goroutines.
// from glog package
func GetCallStacks(all bool) []byte {
// We don't know how big the traces are, so grow a few times if they don't fit.
// Start large, though.
n := 10000
if all {
n = 100000
}
// 4<<10 // 4 KB should be enough
var trace []byte
for i := 0; i < 10; i++ {
trace = make([]byte, n)
bts := runtime.Stack(trace, all)
if bts < len(trace) {
return trace[:bts]
}
n *= 2
}
return trace
}
// GetCallersInfo returns an array of strings containing the file and line number
// of each stack frame leading
func GetCallersInfo(skip, max int) (callers []string) {
var pc uintptr
var ok bool
var line int
var file string
var name string
// callers := []string{}
for i := skip; i < max; i++ {
pc, file, line, ok = runtime.Caller(i)
if !ok {
// The breaks below failed to terminate the loop, and we ran off the
// end of the call stack.
break
}
// This is a huge edge case, but it will panic if this is the case, see #180
if file == "<autogenerated>" {
break
}
f := runtime.FuncForPC(pc)
if f == nil {
break
}
name = f.Name()
parts := strings.Split(file, "/")
file = parts[len(parts)-1]
if len(parts) > 1 {
// dir := parts[len(parts)-2]
callers = append(callers, fmt.Sprintf("%s %s:%d", name, file, line))
}
// Drop the package
segments := strings.Split(name, ".")
name = segments[len(segments)-1]
}
return callers
}
// PanicIfErr if error is not empty
func PanicIfErr(err error) {
if err != nil {
panic(err)
}
}
// Panicf format panic message use fmt.Sprintf
func Panicf(format string, v ...interface{}) {
panic(fmt.Sprintf(format, v...))
}