From 13d0add21c653e2d22a5a95767e6546d1aac3499 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Wed, 15 Mar 2023 18:42:25 +0100 Subject: [PATCH] #121: Remove defer from for loops Fixes #121. `defer` in for loops can possibly lead to leaks. The whole handling including the defer are now moved into anonymous functions outside the for loop and are called form the loop instead. This way the defer is handle when the inline function finishes --- smtp/smtp_test.go | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/smtp/smtp_test.go b/smtp/smtp_test.go index 40b41cb..3d0ad55 100644 --- a/smtp/smtp_test.go +++ b/smtp/smtp_test.go @@ -808,13 +808,7 @@ func TestHello(t *testing.T) { t.Fatalf("Hello server and client size mismatch") } - for i := 0; i < len(helloServer); i++ { - server := strings.Join(strings.Split(baseHelloServer+helloServer[i], "\n"), "\r\n") - client := strings.Join(strings.Split(baseHelloClient+helloClient[i], "\n"), "\r\n") - var cmdbuf strings.Builder - bcmdbuf := bufio.NewWriter(&cmdbuf) - var fake faker - fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) + tf := func(fake faker, i int) error { c, err := NewClient(fake, "fake.host") if err != nil { t.Fatalf("NewClient: %v", err) @@ -871,6 +865,20 @@ func TestHello(t *testing.T) { if err != nil { t.Errorf("Command %d failed: %v", i, err) } + return nil + } + + for i := 0; i < len(helloServer); i++ { + server := strings.Join(strings.Split(baseHelloServer+helloServer[i], "\n"), "\r\n") + client := strings.Join(strings.Split(baseHelloClient+helloClient[i], "\n"), "\r\n") + var cmdbuf strings.Builder + bcmdbuf := bufio.NewWriter(&cmdbuf) + var fake faker + fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf) + + if err := tf(fake, i); err != nil { + t.Error(err) + } if err := bcmdbuf.Flush(); err != nil { t.Errorf("flush failed: %s", err) @@ -1241,6 +1249,13 @@ func serverHandle(c net.Conn, t *testing.T) error { send := smtpSender{c}.send send("220 127.0.0.1 ESMTP service ready") s := bufio.NewScanner(c) + tf := func(config *tls.Config) error { + c = tls.Server(c, config) + defer func() { + _ = c.Close() + }() + return serverHandleTLS(c, t) + } for s.Scan() { switch s.Text() { case "EHLO localhost": @@ -1254,11 +1269,7 @@ func serverHandle(c net.Conn, t *testing.T) error { return err } config := &tls.Config{Certificates: []tls.Certificate{keypair}} - c = tls.Server(c, config) - defer func() { - _ = c.Close() - }() - return serverHandleTLS(c, t) + return tf(config) default: t.Fatalf("unrecognized command: %q", s.Text()) }