Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a function which matches the type of http.HandlerFunc or a type which implements the http.Handler interface.

like image 625
user103576 Avatar asked Jun 15 '11 23:06

user103576


Video Answer


1 Answers

Instead of resorting to reflection, I would do it this way:

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)
}
like image 179
Evan Shaw Avatar answered Oct 07 '22 02:10

Evan Shaw