在main
中,应用程序就这样启动:
// ...
func main () {
initializeAppDefault()
go lib.GetData()
http.HandleFunc("/_ah/somepoint", lib.SomeHandler)
// ..
func initializeAppDefault() *firebase.App {
// [START initialize_app_default]
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// [END initialize_app_default]
return app
}
在SomeHandler
中,我需要initializeAppDefault
返回的应用,以验证JSON Web令牌(JWT)。
func SomeHandler(w http.ResponseWriter, r *http.Request) {
// Set content type:
w.Header().Set("Content-Type", "application/json")
if r.Header != nil {
ReqToken := r.Header.Get("Authorization")
splitToken := strings.Split(ReqToken, "Bearer")
ReqToken = splitToken[1]
fmt.Println(ReqToken)
// Verify JWT
// If it's invalid, return?
verifyIDToken(app, ReqToken)
// How do I pass the app in here?
func verifyIDToken(app *firebase.App, idToken string) *auth.Token {
// ...
我的问题是,当通过调用main.go
在initializeAppDefault()
文件中初始化应用时,如何将其传递给处理SomeHandler
请求的/_ah/somepoint
?
答案 0 :(得分:1)
将任意依赖项传递给HTTP处理程序函数的方法是返回一个闭包:
func myHandler(a *Something, b *SomethingElse) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The body of the handler here, using a and b
}
}
然后你将它用作:
http.Handle("/some/path", myHandler(a, b))
答案 1 :(得分:1)
使用*firebase.App
的成员定义新的结构类型:
type myapp struct {
fbapp *firebase.App
// here can be other common states and resources
// like sessions, db connections, etc...
}
将处理程序定义为该类型的方法
func (ma *myapp) SomeHandler(w http.ResponseWriter, r *http.Request) {
// here you have access to all members of myapp, including ma.fbapp
// also you can use your lib.* funcs here
}
在您的主要内容中,您需要创建myapp
并将其传递给http.HandleFunc
。
func main () {
ma := &myapp{
fbapp: initializeAppDefault()
}
go lib.GetData()
http.HandleFunc("/_ah/somepoint", ma.SomeHandler)
这是一种常见的模式。看看我如何使用它in my interview task:注意如何定义处理程序,how they getting access to the common s.store和how main function inits all common resources, creates router and runs it。