Passing Context to Interface Methods

后端 未结 2 1286
暖寄归人
暖寄归人 2021-02-08 23:08

Somewhat inspired by this article last week, I\'m toying with refactoring an application I have to more explicitly pass context (DB pools, session stores, etc) to my handlers.

2条回答
  •  不要未来只要你来
    2021-02-08 23:38

    I would use a closure and do something like this:

    func IndexHandler(a *appContext) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *httpRequest) {
            // ... do stuff
            fmt.Fprintf(w, "db is %q and store is %q\n", a.db, a.store)
        })
    }
    

    And just use the returned http.Handler.

    You'll just have to make sure your appContext is goroutine-safe.

提交回复
热议问题