drde3456 2018-01-09 09:20
浏览 19
已采纳

如何通过功能传递应用程序?

In main, the app is started as such:

// ...

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
", err)
    }
    // [END initialize_app_default]
    return app
}

In SomeHandler, I need the app which initializeAppDefault returns, to verify a JSON Web Token(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 {
// ... 

My question is, when the app is initialized in the main.go file by invoking initializeAppDefault(), how do I pass it to the SomeHandler which handles requests at /_ah/somepoint?

  • 写回答

2条回答 默认 最新

  • dongpu5600 2018-01-09 10:22
    关注

    The way to pass arbitrary dependencies into an HTTP handler function is by returning a closure:

    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
        }
    }
    

    Then you'll use it as:

    http.Handle("/some/path", myHandler(a, b))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献