Memory leak in Go http standard library?

后端 未结 1 570
北恋
北恋 2021-02-01 08:18

Have a Go binary implement an http server:

package main

import (
    \"net/http\"
)

func main() {
    http.ListenAndServe(\":8080\", nil)
}

I

相关标签:
1条回答
  • 2021-02-01 08:56

    From the heap pprof you have provided in comments, it looks like you are leaking memory via gorilla/sessions and gorilla/context (almost 400MB).

    Refer to this ML thread: https://groups.google.com/forum/#!msg/gorilla-web/clJfCzenuWY/N_Xj9-5Lk6wJ and this GH issue: https://github.com/gorilla/sessions/issues/15

    Here is a version that leaks extremely quickly:

    package main
    
    import (
        "fmt"
        // "github.com/gorilla/context"
        "github.com/gorilla/sessions"
        "net/http"
    )
    
    var (
        cookieStore = sessions.NewCookieStore([]byte("cookie-secret"))
    )
    
    func main() {
        http.HandleFunc("/", defaultHandler)
        http.ListenAndServe(":8080", nil)
    }
    
    func defaultHandler(w http.ResponseWriter, r *http.Request) {
        cookieStore.Get(r, "leak-test")
        fmt.Fprint(w, "Hi there")
    }
    

    Here is one that cleans up and has a relatively static RSS:

    package main
    
    import (
        "fmt"
        "github.com/gorilla/context"
        "github.com/gorilla/sessions"
        "net/http"
    )
    
    var (
        cookieStore = sessions.NewCookieStore([]byte("cookie-secret"))
    )
    
    func main() {
        http.HandleFunc("/", defaultHandler)
        http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
    }
    
    func defaultHandler(w http.ResponseWriter, r *http.Request) {
        cookieStore.Get(r, "leak-test")
        fmt.Fprint(w, "Hi there")
    }
    
    0 讨论(0)
提交回复
热议问题