我正在教自己使用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))
我想要做的是&#34; stack&#34;多个功能包含更多功能。我想添加一个通过.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
错误。我没有
以前在关闭时工作很多,我觉得我在这里肯定会遗漏一些东西。
感谢您的帮助!
答案 0 :(得分:2)
function(w, req)
是没有返回值的函数调用,而addHeader
期望函数作为其参数。
如果你想组合两个包装函数,你可能想要这样的东西:
func HandleWrapper(function HandleFunc) HandleFunc {
return logPanics(addHeader(function))
}