http.Handle(Handler或HandlerFunc)

use*_*576 5 reflection interface http go

如何实现以下功能?

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{})
Run Code Online (Sandbox Code Playgroud)

handle()传递一个匹配http.HandlerFunc类型的函数或一个实现http.Handler接口的类型.

Eva*_*haw 8

我不是采用反思,而是这样做:

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)
}
Run Code Online (Sandbox Code Playgroud)