背景
在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。
步骤
实现函数RecursiveDepthChecker
func RecursiveDepthChecker(max int) bool { //注意,这里我们跳过了本函数自己的栈,找到父调用的函数名 caller, _, _, _ := runtime.Caller(1) currentFuncName := runtime.FuncForPC(caller).Name() stack := make([]byte, 65535*1) //max 1MB stack traceback //由于Golang Runtime中很多关于栈的函数未导出,无法使用。因此使用最肮脏的字符串检测方法 runtime.Stack(stack, false) start := 0 depth := 0 for { count := strings.Index(string(stack[start:]), currentFuncName) if count >= 0 { start += count + len(currentFuncName) depth++ } else { break } } if depth > max { return false } return true}
在需要进行检测的函数用引入检查即可
func TFunc() { fmt.Println("Start Caller...") if !RecursiveDepthChecker(5) { fmt.Println("Stack Overflow") return } TFunc()}