Http.Handle (handler or HandlerFunc)

How is the following function implemented?

func handle(pattern string, handler interface{}) {
    // ... what goes here? ...
    http.Handle(pattern, ?)
}

handle("/foo", func(w http.ResponseWriter, r http.Request) { io.WriteString(w, "foo") }
handle("/bar", BarHandler{})

handle () is passed either by a function that corresponds to the http.HandlerFunc type or to a type that implements the http.Handler interface.

+5
source share
2 answers

Instead of resorting to reflection, I would do it as follows:

func handle(pattern string, handler interface{}) {
    var h http.Handler
    switch handler := handler.(type) {
    case http.Handler:
        h = handler
    case func(http.ResponseWriter, *http.Request):
        h = http.HandlerFunc(handler)
    default:
        // error
    }
    http.Handle(pattern, h)
}
+7
source

First we need to introduce the term “reflections” in Java / C # terminology, RTTI in C ++ terminology. It is pretty simple. The compiler stores data to find out what type of instance is var i SomeTypeat run time. Go supports reflection and how it finds out what type is handlerat run time.

handle .

package main
import ("reflect";"http")
type fakeHandler struct{}
func (frw *fakeHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}

func handle(pattern string, handler interface{}) {
    handlerInterface := reflect.TypeOf(new(http.Handler)).Elem()
    handlerFunction  := reflect.TypeOf(new(http.HandlerFunc)).Elem()
    t := reflect.TypeOf(handler)
    if t.Implements(handlerInterface) {fmt.Println("http.Handler")}
    //http.HandlerFunc is a different type than
    // func(http.ResponseWriter, *http.Request), but we can do
    // var hf HandlerFunc = func(http.ResponseWriter, *http.Request){}
    if t.AssignableTo(handlerFunction) {fmt.Println("http.HandleFunc")}
}
func f(http.ResponseWriter, *http.Request) {}
func main() {
    handle("",&fakeHandler{})
    handle("",f)
}
+2

All Articles