[英]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. handle()传递一个匹配http.HandlerFunc类型的函数或一个实现http.Handler接口的类型。
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)
}
First we need to introduce the term "reflections" in Java/C#'s terminology, RTTI in C++'s terminology. 首先,我们需要在Java / C#的术语中引入术语“反射”,在C ++的术语中引入RTTI。 It's quite simple actually.
实际上这很简单。 The compiler keeps data to find out what is the type of an instance
var i SomeType
during runtime. 编译器保留数据以在运行时期间找出实例
var i SomeType
的类型。 Go supports reflection, and that's how it finds out what's the type of handler
during runtime. Go支持反射,这就是它如何在运行时找出
handler
的类型。
The handle
function uses the reflection. handle
函数使用反射。 A crude example 一个粗略的例子
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.