From bbd5a768a8b18eb355ae67c5d090cfbd94847e08 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Tue, 28 Jun 2022 13:38:46 +0100 Subject: [PATCH] remotedb/grpcdb: fix net.Listener leak in ListenAndServe Uses Go's named return value feature to properly check and ensure that if any error is encountered, that we properly invoke .Close for the bound net listener inside of ListenAndServe. Fixes #268 --- remotedb/grpcdb/server.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/remotedb/grpcdb/server.go b/remotedb/grpcdb/server.go index 3cedca8c7..38e38d6fe 100644 --- a/remotedb/grpcdb/server.go +++ b/remotedb/grpcdb/server.go @@ -16,11 +16,17 @@ import ( // ListenAndServe is a blocking function that sets up a gRPC based // server at the address supplied, with the gRPC options passed in. // Normally in usage, invoke it in a goroutine like you would for http.ListenAndServe. -func ListenAndServe(addr, cert, key string, opts ...grpc.ServerOption) error { +func ListenAndServe(addr, cert, key string, opts ...grpc.ServerOption) (rerr error) { ln, err := net.Listen("tcp", addr) if err != nil { return err } + defer func() { + if rerr != nil { + _ = ln.Close() + } + }() + srv, err := NewServer(cert, key, opts...) if err != nil { return err