根据接收器类型在Go中更改函数行为

huangapple go评论79阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年11月4日 02:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/26720557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定