服务器的Golang自定义处理程序

I want to use a custom method on http.ListenAndServe

Here is what I have

http.ListenAndServe(":8000", ErrorHandler)

func ErrorHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h.ServeHTTP(w, r)
    })
}

Error

cannot use ErrorHandler (type func(http.Handler) http.Handler) as type http.Handler in argument to http.ListenAndServe:
        func(http.Handler) http.Handler does not implement http.Handler (missing ServeHTTP method)

How can I add a custom method to ListenAndServe?

Your ErrorHandler(h http.Handler) http.Handler func is basically just "middleware" and not a real handler. It takes a handler h and returns a new handler. http.StripPrefix is an example of such "middleware".

If you don't want middleware, but just a handler then you need to define your function a little differently:

func ErrorHandler(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}

Now you can pass your ErrorHandler to ListenAndServe although you still need to cast it to the proper http.Handler type like so:

http.ListenAndServe(":8000", http.HandlerFunc(ErrorHandler))

http.HandlerFunc is an adapter that turns a function, if it has the right signature, into an http.Handler.

Finally, if you don't like the casting, you'll need to define a type instead of a just a function and you'll need to define a method on that type that is required for it to satisfy the http.Handler interface type.

type ErrorHandler struct{}

func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // do stuff with r and w
}

http.ListenAndServe(":8080", &ErrorHandler{})

Read more about it here https://golang.org/pkg/net/http/#Handler