Inheritance 根据Go中的接收器类型更改函数行为
我希望函数的行为根据接收器而改变。或者说,我希望有一种方法能够接收不同的接收器作为输入。比如说Inheritance 根据Go中的接收器类型更改函数行为,inheritance,go,Inheritance,Go,我希望函数的行为根据接收器而改变。或者说,我希望有一种方法能够接收不同的接收器作为输入。比如说 type handler func(http.ResponseWriter, *http.Request, *Context) type requireloggedinhandler handler func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := setupContext(...) //
type handler func(http.ResponseWriter, *http.Request, *Context)
type requireloggedinhandler handler
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := setupContext(...)
// NEXT LINE IS THE KEY LINE
if (reflect.TypeOf(h) == main.requireloggedinhandler) {
if !checkedLoggedIn(ctx) {
http.Redirect(...)
return
}
}
h(w, r, ctx)
}
但问题是,一旦我们得到ServeHTTP,类型必须是handler,而不是requireloggedinhandler。这行不通
r.HandleFunc("/", requireloggedinhandler(MyFunc).ServeHTTP)
我可以输入ServeHTTP作为handler的继承接口吗?不要使用r.HandleFunc使用stright r.Handle/,MyFunc