【发布时间】: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