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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c