英文:
Changing function behavior based on reciever type in Go
问题
我想要根据接收器的不同来改变函数的行为。或者说,我希望一个方法能够接受不同的接收器作为输入。例如:
type handler func(http.ResponseWriter, *http.Request, *Context)
type requireloggedinhandler handler
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := setupContext(...)
// 下一行是关键行
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 的继承接口吗?
英文:
I want the behavior of a function to change based on the receiver. Or really, I want a method to be able to take in different receivers as input. For instance
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)
}
But the issue is once we get to ServeHTTP the type has to be handler, not requireloggedinhandler. eg this won't work
r.HandleFunc("/", requireloggedinhandler(MyFunc).ServeHTTP)
Can I enter ServeHTTP as an inherited interface of handler?
答案1
得分: 3
不要使用r.HandleFunc
,而是直接使用r.Handle("/", MyFunc)
。
英文:
Don't use r.HandleFunc
use straight r.Handle("/", MyFunc)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论