gpt4 book ai didi

google-app-engine - Appengine with Go : Is there a http. Handle prehook 或类似的东西?

转载 作者:IT王子 更新时间:2023-10-29 01:13:11 26 4
gpt4 key购买 nike

假设我有以下 init 函数路由请求。

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()
//Actual handler code
...
...
}

但是,有没有一种方法可以在不将函数调用放入每个处理程序的情况下获取数据?这甚至是 Go 一开始就希望你做的事情吗?

最佳答案

你有两个选择。

  1. 你可以实现http.Handler接口(interface)
  2. 你用一个包装器 HandleFunc 包装你所有的 http.HandlerFunc

因为看起来您想要一些简单的东西,所以我将说明 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)
}

关于google-app-engine - Appengine with Go : Is there a http. Handle prehook 或类似的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16467716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com