dongshang1979 2018-01-11 03:01
浏览 43
已采纳

如何在Google App Engine标准环境下的Gorilla会话中避免内存泄漏?

I'm using Gorilla to enable session variables on Google App Engine. So far I imported "github.com/gorilla/sessions" only, but Gorilla's page says:

If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))

My question is how do I adapt this for the App Engine Standard Environment, which as far as I know does not use http.ListenAndServe by default. My code looks like this:

package test

import (
    "fmt"
    "net/http"
    "github.com/gorilla/sessions"   
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {

    var cookiestore =  sessions.NewCookieStore([]byte("somesecret"))
    session, _ := cookiestore.Get(r, "session")
    session.Values["foo"] = "bar"

    fmt.Fprintf(w, "session value is %v", session.Values["foo"])

}

Would I get a memory leak this way?

  • 写回答

2条回答 默认 最新

  • douluhaikao93943 2018-01-11 09:12
    关注

    The doc you quoted tells everything you need to do: wrap your handlers using context.ClearHandler(). Since you "only" have a handler function and not an http.Handler, you may use the http.HandlerFunc adapter to get a value that implements http.Handler:

    func init() {
        http.Handle("/", context.ClearHandler(http.HandlerFunc(handler)))
    }
    

    You need to do this for every handler you register. That's why the doc mentions that it's easier to just wrap the root handler you pass to http.ListenAndServe() (and that way you don't have to wrap the other, non-top-level handlers). But this isn't the only way, just the easiest / shortest.

    If you don't call http.ListenAndServe() yourself (as in App Engine), or you don't have a single root handler, then you need to wrap all handlers manually that you register.

    Note that the handler returned by context.ClearHandler() does nothing magical, all it does is call context.Clear() after calling the handler you pass. So you may just as easily call context.Clear() in your handler to achieve the same effect.

    If you do so, one important thing is to use defer as if for some reason context.Clear() would not be reached (e.g. a preceding return statement is encountered), you would again leak memory. Deferred functions are called even if your function panics. So it should be done like this:

    func handler(w http.ResponseWriter, r *http.Request) {
        defer context.Clear(r)
    
        var cookiestore =  sessions.NewCookieStore([]byte("somesecret"))
        session, _ := cookiestore.Get(r, "session")
        session.Values["foo"] = "bar"
    
        fmt.Fprintf(w, "session value is %v", session.Values["foo"])
    }
    

    Also note that the session store creation should only be done once, so move that out from your handler to a global variable. And do check and handle errors to save you some headache. So the final suggested code is this:

    package test
    
    import (
        "fmt"
        "net/http"
        "log"
    
        "github.com/gorilla/context"
        "github.com/gorilla/sessions"
    )
    
    func init() {
        http.Handle("/", context.ClearHandler(http.HandlerFunc(handler)))
    }
    
    var cookiestore =  sessions.NewCookieStore([]byte("somesecret"))
    
    func handler(w http.ResponseWriter, r *http.Request) {
        session, err := cookiestore.Get(r, "session")
        if err != nil {
            // Handle error:
            log.Printf("Error getting session: %v", err)
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        session.Values["foo"] = "bar"
    
        fmt.Fprintf(w, "session value is %v", session.Values["foo"])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用