如何包装自定义HandlerFunc

I have defined a CustomHandler (struct which implements ServerHTTP, and has a HandlerFunc that returns an error)

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
}

How can I wrap my CustomHandler?

I have tried this, but I keep getting not enough arguments.

func myMiddle(h CustomHandler) CustomHandler {
  return h.CusomHandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
    h.ServerHTTP(w, r)
    return nil
  })
}

You can simply do that:

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 {
        ...
    }
}

And use it like:

func home(w http.ResponseWriter, r *http.Request) error {
    ...
}

func main() {
    http.Handle("/", handler(home))
}

First define CustomHandler like this:

type CustomHandler struct{}

then ServeHTTP like this:

func (c CustomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s", msg1)
}

See this working sample code:

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>
`

Then run the above code then open http://127.0.0.1/
output:

Welcome Home

Don't make so many spelling mistakes in your code.

  • ServerHTTP should be ServeHTTP
  • Handeler should be Handler
  • ServerHttp should be ServeHTTP
  • CusomHandlerFunc should be CustomHandlerFunc

When you have fixed these misspellings, you have a better chance that your code works.