如何包装自定义HandlerFunc

时间:2016-08-07 19:59:57

标签: go

我已经定义了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
  })
}

3 个答案:

答案 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

修复这些拼写错误后,您的代码可能会更有效。