2017年1月2日星期一

Do not use Golang's http.ListenAndServe() in production!

The default http.Server in source code:

func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}

It lacks the ReadTimeout or IdleTimeout(go1.8), which will result in many unclosed connections if the client didn't close the connections explicitly. And soon, the server will complain about too many opened files.

instead, using the code like below to avoid the problem

func main() { http.HandleFunc("/rest", realtime.HandleInfo) s := &http.Server{ Addr: ":9001", Handler: http.DefaultServeMux, ReadTimeout: time.Second * 60, //important for closing client with timeout WriteTimeout: time.Second * 60, } log.Fatal(s.ListenAndServe()) }