-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreflect.go
75 lines (64 loc) · 1.57 KB
/
reflect.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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/essentials source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package ess
import (
"path/filepath"
"reflect"
"runtime"
"strings"
)
// CallerInfo struct stores Go caller info
type CallerInfo struct {
QualifiedName string
FunctionName string
FileName string
File string
Line int
}
// FunctionInfo structs Go function info
type FunctionInfo struct {
Name string
Package string
QualifiedName string
}
// GetFunctionInfo method returns the function name for given interface value.
func GetFunctionInfo(f interface{}) (fi *FunctionInfo) {
if f == nil {
fi = &FunctionInfo{}
return
}
defer func() {
if r := recover(); r != nil {
// recovered
fi = &FunctionInfo{}
}
}()
info := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
info = strings.Replace(info, "%2e", ".", -1)
idx := strings.LastIndexByte(info, '.')
fi = &FunctionInfo{
Name: info[idx+1:],
Package: info[:idx-1],
QualifiedName: info,
}
return
}
// GetCallerInfo method returns caller's QualifiedName, FunctionName, File,
// FileName, Line Number.
func GetCallerInfo() *CallerInfo {
pc, file, line, ok := runtime.Caller(1)
if !ok {
file = "???"
line = 0
}
fn := runtime.FuncForPC(pc).Name()
fn = strings.Replace(fn, "%2e", ".", -1)
return &CallerInfo{
QualifiedName: fn,
FunctionName: fn[strings.LastIndex(fn, ".")+1:],
File: file,
FileName: filepath.Base(file),
Line: line,
}
}