The function `notfound` is a plain function. It has a specific signature,
(w http.ResponseWriter, r *http.Request). There is a type, HandlerFunc,
with the following specification:

type HandlerFunc func(ResponseWriter, *Request)

Types in Go are "generative", so the HandlerFunc type is different from a
plain function. But if we wrap it, like your code does, we "lift" the plain
function into becoming a HandlerFunc. Now, why do we do that? Well,
HandlerFunc implements the Handler interface:

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

And the http server uses the Handler interface all over the place. This
allows us to "adapt" any function with the right signature into an
http.Handler. Had we just passed the plain function, the trouble is that it
doesn't implement the ServeHTTP method. And we need this for the Handler
interface.

In short, we can "tag" a function as being an http.Handler and use it as
one in our web server by adapting through the HandlerFunc type.

Other people might have comments here as to my specificity wrt the
explanation.

On Sat, Apr 4, 2020 at 4:10 AM joe mcguckin <j...@via.net> wrote:

> I see some code like:
>
>
>           r.NotFoundHandler =http.HandlerFunc(notfound)
>
> Where notfound() has the signature of
>
>           func notfound(w http.ResponseWriter, r *http.Request)
>
> What is HandlerFunc() doing? It’s not a function. Is it some sort of type
> coercion or casting?
>
> I can see how casting that might work with simple values
> (e.g.numbers,integers, etc)  but functions?
>
> The web docs say:
>     The HandlerFunc type is an adapter to allow the use of ordinary
> functions as HTTP handlers. If f is a function with the appropriate
> signature, HandlerFunc(f) is a Handler that calls f.
>
> If notfound() is ' func notfound(w http.ResponseWriter, r *http.Request)’,
> what is it being converted into?
>
> Why is this needed?
>
> Thanks,
>
> Joe
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/C594C073-3DF8-4CD1-8C43-59AE59AADF92%40via.net
> .
>


-- 
J.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAGrdgiW0PY0ReswiveVV%3Dt6W1K6RydmTVh1hk6nE7DnGApBAHQ%40mail.gmail.com.

Reply via email to