I arrived here when looking into how the typical http middleware implementation returned a http.Handler
interface without defining a ServeHTTP
method for the anonymous function it returns:
func LoggingMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.String())
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
Here, the anonymous function is being converted to the HandlerFunc
type to fulfill the interface requirements: http.HandlerFunc(fn)
Even though the anonymous function doesn't directly fulfill the Handler
interface itself by implementing a ServeHTTP
method, the HandlerFunc type that it's converted to does implement a ServeHTTP
method.
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
Here's a stripped down playground example: https://play.golang.org/p/JX0hrcXyj6Q
package main
import (
"fmt"
)
type Walker interface {
Walk() // interface to be fulfilled by anonymous function
}
type WalkerFunc func()
// Walk method satisfies Walker interface
func (wf WalkerFunc) Walk() {
fmt.Println("start walking")
wf()
fmt.Printf("stop walking\n\n")
}
func main() {
// use type conversion to convert anonymous function to WalkerFunc type, satisfying Walker interface
WalkerFunc(func() { fmt.Println("chew gum") }).Walk()
WalkerFunc(func() { fmt.Println("smell roses") }).Walk()
}
/*
OUTPUT:
start walking
chew gum
stop walking
start walking
smell roses
stop walking
*/