Voglio sapere cosa sta succedendo qui.Funzione implementazione interfaccia
V'è l'interfaccia per un gestore http:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
Questa implementazione Credo di capire.
type Counter int
func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
fmt.Fprintf(c, "counter = %d\n", ctr);
ctr++;
}
Dalla mia comprensione si è che il tipo di "Counter" implementa l'interfaccia dal momento che ha un metodo che ha la firma richiesto. Fin qui tutto bene. Quindi questo esempio è dato:
func notFound(c *Conn, req *Request) {
c.SetHeader("Content-Type", "text/plain;", "charset=utf-8");
c.WriteHeader(StatusNotFound);
c.WriteString("404 page not found\n");
}
// Now we define a type to implement ServeHTTP:
type HandlerFunc func(*Conn, *Request)
func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
f(c, req) // the receiver's a func; call it
}
// Convert function to attach method, implement the interface:
var Handle404 = HandlerFunc(notFound);
Qualcuno può approfondire perché o come queste varie funzioni combaciano?
Ok penso di averlo capito ora, la cosa che mi ha fatto inciampare è stata la conversione di notFound in HandlerFunc. Dopo aver riletto la sezione conversioni di go efficaci, è più chiaro come ciò possa essere applicato anche alle funzioni. http://golang.org/doc/effective_go.html#conversions – mbarkhau