我可以创建一个只能与延迟一起使用的函数吗?

时间:2014-12-24 07:37:59

标签: go deferred

例如:

package package

// Dear user, CleanUp must only be used with defer: defer CleanUp()
func CleanUp() {
    // some logic to check if call was deferred
    // do tear down
}

用户名代码:

func main() {
    package.CleanUp() // PANIC, CleanUp must be deferred!
}

但如果用户运行,一切都应该没问题:

func main() {
   defer package.CleanUp() // good job, no panic
}

我已经尝试过的事情:

func DeferCleanUp() {
    defer func() { /* do tear down */ }()
    // But then I realized this was exactly the opposite of what I needed
    // user doesn't need to call defer CleanUp anymore but...
}
// now if the APi is misused it can cause problems too:
defer DeferCleanUp() // a defer inception xD, question remains.

1 个答案:

答案 0 :(得分:4)

好吧,根据OP请求和笑声,我通过查看调用堆栈并应用一些启发式方法来发布这种hacky方法来解决这个问题。

免责声明:请勿在实际代码中使用此功能。我不认为延期检查甚至是件好事。所以,请不要忘记:)

另请注意:此方法仅在可执行文件和源位于同一台计算机上时才有效。

链接到要点:https://gist.github.com/dvirsky/dfdfd4066c70e8391dc5(这不适合在操场上工作,因为你无法在那里阅读源文件)

package main

import(
    "fmt"
    "runtime"
    "io/ioutil"
    "bytes"
    "strings"
)




func isDeferred() bool {

    // Let's get the caller's name first
    var caller string
    if fn, _, _, ok  := runtime.Caller(1); ok {
        caller = function(fn)
    } else {
        panic("No caller")
    }

    // Let's peek 2 levels above this - the first level is this function,
    // The second is CleanUp()
    // The one we want is who called CleanUp()
    if _, file, line, ok  := runtime.Caller(2); ok {

        // now we actually need to read the source file
        // This should be cached of course to avoid terrible performance
        // I copied this from runtime/debug, so it's a legitimate thing to do :)
        data, err := ioutil.ReadFile(file)
        if err != nil {
            panic("Could not read file")
        }

        // now let's read the exact line of the caller 
        lines := bytes.Split(data, []byte{'\n'})
        lineText := strings.TrimSpace(string(lines[line-1]))
        fmt.Printf("Line text: '%s'\n", lineText)


        // Now let's apply some ugly rules of thumb. This is the fragile part
        // It can be improved with regex or actual AST parsing, but dude...
        return lineText == "}" ||  // on simple defer this is what we get
               !strings.Contains(lineText, caller)  || // this handles the case of defer func() { CleanUp() }()
               strings.Contains(lineText, "defer ")


    } // not ok - means we were not clled from at least 3 levels deep

    return false
}

func CleanUp() {
    if !isDeferred() {
        panic("Not Deferred!")
    }


}

// This should not panic
func fine() {
    defer CleanUp() 

    fmt.Println("Fine!")
}


// this should not panic as well
func alsoFine() {
    defer func() { CleanUp() }()

    fmt.Println("Also Fine!")
}

// this should panic
func notFine() {
    CleanUp() 

    fmt.Println("Not Fine!")
}

// Taken from the std lib's runtime/debug:
// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) string {
    fn := runtime.FuncForPC(pc)
    if fn == nil {
        return ""
    }
    name := fn.Name()
    if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 {
        name = name[lastslash+1:]
    }
    if period := strings.Index(name, "."); period >= 0 {
        name = name[period+1:]
    }
    name = strings.Replace(name, "·", ".", -1)
    return name
}

func main(){
    fine()
    alsoFine()
    notFine()
}