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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题