Go 尝试包装函数时函数用作值错误
我正在自学如何使用Way to Go book的net/http包。他提到了一种将处理函数包装在闭包中的方法,这种方法可以处理Go 尝试包装函数时函数用作值错误,go,Go,我正在自学如何使用Way to Go book的net/http包。他提到了一种将处理函数包装在闭包中的方法,这种方法可以处理恐慌,如下所示: func Index(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, "<h2>Index</h2>") } func logPanics(function
恐慌
,如下所示:
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)
}
}
我想做的是“堆叠”多个函数以包含更多功能。我想添加一个闭包,通过.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 logPanics(addHeader(function))
}
但我认为,在使用包装器函数将这些函数分开的同时,将其缩短会更好:
func HandleWrapper(function HandleFunc) HandleFunc {
return func(w http.ResponseWriter, req *http.Request) {
logPanics(addHeader(function(w, req)))
}
}
但是我得到一个函数(w,req)用作值错误。我没有
以前在闭包方面做了很多工作,我觉得我肯定错过了一些东西
谢谢你的帮助 function(w,req)
是一个没有返回值的函数调用,而addHeader
需要一个函数作为其参数
如果要组合这两个包装器函数,可能需要如下内容:
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 logPanics(addHeader(function))
}
谢谢就这样。据我所知,包装器函数返回函数对象而不执行代码——所有代码都是在函数实际被调用时执行的,对吗?是的。因此,为了组成两个包装器,没有必要截获对HandlerFunc
的实际调用。