我已经定义了CustomHandler
(实现ServerHTTP
的结构,并且有HandlerFunc
返回错误)
type CustomHandler struct{
HandlerFunc func(w http.ResponseWriter, r *http.Request) error
}
type (c CustomHandler) ServerHTTP(w http.ResponseWriter, r *http.Request) {
err := c.Handeler.ServerHttp(w, r)
// Handler error
}
如何包装CustomHandler
?
我试过这个,但我一直没有得到足够的论据。
func myMiddle(h CustomHandler) CustomHandler {
return h.CusomHandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
h.ServerHTTP(w, r)
return nil
})
}
答案 0 :(得分:0)
你可以这样做:
type handler func(w http.ResponseWriter, r *http.Request) error
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h(w, r); err != nil {
...
}
}
并使用它:
func home(w http.ResponseWriter, r *http.Request) error {
...
}
func main() {
http.Handle("/", handler(home))
}
答案 1 :(得分:0)
首先像这样定义CustomHandler
:
type CustomHandler struct{}
然后ServeHTTP
像这样:
func (c CustomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", msg1)
}
请参阅此工作示例代码:
package main
import "fmt"
import "net/http"
func main() {
http.Handle("/", CustomHandler{})
http.ListenAndServe(":80", nil)
}
type CustomHandler struct{}
func (c CustomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", msg1)
}
var msg1 string = `
<!DOCTYPE html>
<html>
<head>
<title>Welcome Home</title>
</head>
<body>
Welcome Home
</body>
</html>
`
然后运行上面的代码,然后打开http://127.0.0.1/
输出:
Welcome Home
答案 2 :(得分:0)
不要在代码中犯很多拼写错误。
ServerHTTP
应为ServeHTTP
Handeler
应为Handler
ServerHttp
应为ServeHTTP
CusomHandlerFunc
应为CustomHandlerFunc
修复这些拼写错误后,您的代码可能会更有效。