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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100