英文:
Appengine with Go: Is there a http.Handle prehook or something similar?
问题
假设我有以下的初始化函数来路由请求。
func init() {
http.HandleFunc("/user", handler1)
http.HandleFunc("/user/profile", handler2)
http.HandleFunc("/user/post", handler3)
....
....
}
所有这些都需要我有用户的个人资料。
我知道我可以这样做
func handler1(w http.ResponseWriter, r *http.Request) {
getUserdata()
//实际的处理程序代码
...
...
}
但是,有没有一种方法可以在每个处理程序中不放置函数调用的情况下获取数据?这是Go是否希望你首先这样做的事情吗?
英文:
Suppose I have the following init function routing requests.
func init() {
http.HandleFunc("/user", handler1)
http.HandleFunc("/user/profile", handler2)
http.HandleFunc("/user/post", handler3)
....
....
}
All of these require that I have the user's profile.
I know I can
func handler1(w http.ResponseWriter, r *http.Request) {
getUserdata()
//Actual handler code
...
...
}
But, is there a way I can get the data without putting the function call in every handler? Is this even something Go would want you to do in the first place?
答案1
得分: 10
你有两个选择。
- 你可以实现
http.Handler
接口 - 你可以用一个包装器
HandleFunc
包装所有的http.HandlerFunc
。
由于看起来你想要简单的东西,我将说明包装器的用法
func Prehook(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
getUserData()
f(w, r)
}
}
func init() {
// 在处理程序之前调用getUserData()
http.HandleFunc("/user", Prehook(handler1))
// 在处理程序之前不要调用getUserData()
http.HandleFunc("/user/profile", handler2)
}
英文:
You have two options.
- You can inplement the
http.Handler
interface - You Wrap all your
http.HandlerFunc
with a wrapper HandleFunc.
Since it looks like you want something simple I'll illustrate the WRapper
func Prehook(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
getUserData()
f(w, r)
}
}
func init() {
// use getUserData() call before your handler
http.HandleFunc("/user", Prehook(handler1))
// Don't use getUserData call before your handler
http.HandleFunc("/user/profile", handler2)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论