【问题标题】:function used as value error while trying to wrap functions尝试包装函数时函数用作值错误
【发布时间】:2013-11-22 16:18:02
【问题描述】:

我正在通过 The Way to Go 这本书自学使用 net/http 包。他提到了一种将处理函数包装在处理 panics 的闭包中的方法,如下所示:

func Index(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    fmt.Fprint(w, "<h2>Index</h2>")
}

func logPanics(function HandleFunc) HandleFunc {
    return func(w http.ResponseWriter, req *http.Request) {
        defer func() {
            if err := recover(); err != nil {
              log.Printf("[%v] caught panic: %v", req.RemoteAddr, err)
            }
        }()
        function(w, req)
    }
}

然后像这样使用上面的方法调用 http.HandleFunc:

http.HandleFunc("/", logPanics(Index))

我想做的是“堆叠”多个功能以包含更多功能。我想添加一个通过.Header().Set(...) 添加mime 类型的闭包,我可以这样称呼它:

func addHeader(function HandleFunc) HandleFunc {
    return func(w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Content-Type", "text/html")
        function(w, req)
    }
}
(then in main())
http.HandleFunc("/", logPanics(addHeader(Index)))

但我认为缩短它同时仍然使用包装函数将这些函数分开会很好:

func HandleWrapper(function HandleFunc) HandleFunc {
    return func(w http.ResponseWriter, req *http.Request) {
        logPanics(addHeader(function(w, req)))
    }
}

但我收到function(w, req) used as value 错误。我没有 以前在闭包方面工作过很多,我觉得我肯定在这里遗漏了一些东西。

感谢您的帮助!

【问题讨论】:

    标签: go


    【解决方案1】:

    function(w, req) 是一个没有返回值的函数调用,而addHeader 需要一个函数作为其参数。

    如果你想组合这两个包装函数,你可能想要这样的东西:

    func HandleWrapper(function HandleFunc) HandleFunc {
        return logPanics(addHeader(function))
    }
    

    【讨论】:

    • 谢谢!就是这样。据我了解,包装函数在不执行代码的情况下返回函数对象——所有代码都在函数被实际调用时执行,对吧?
    • 是的。因此,无需拦截对HandlerFunc 的实际调用即可组成两个包装器。
    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 2021-02-24
    • 2020-04-10
    • 2012-07-14
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多