一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述

背景

在递归处理的调用中,在具体的工程实践中通常会引入递归深度检测,防止由于错误的数据形成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。函数

步骤

实现函数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()
}
相关文章
相关标签/搜索