From 1d16d24ad6f53ae7d5f5baf2d8d3849a743acbe8 Mon Sep 17 00:00:00 2001 From: Bryce Kahle Date: Fri, 21 Jun 2024 11:40:00 -0700 Subject: [PATCH] use closeOnError pattern --- internal/epoll/poller.go | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/internal/epoll/poller.go b/internal/epoll/poller.go index 84c2acbe6..977d1fd0e 100644 --- a/internal/epoll/poller.go +++ b/internal/epoll/poller.go @@ -27,37 +27,42 @@ type Poller struct { flushEvent *eventFd } -func New() (*Poller, error) { +func New() (_ *Poller, err error) { + closeFDOnError := func(fd int) { + if err != nil { + unix.Close(fd) + } + } + closeEventFDOnError := func(e *eventFd) { + if err != nil { + e.close() + } + } + epollFd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC) if err != nil { return nil, fmt.Errorf("create epoll fd: %v", err) } + defer closeFDOnError(epollFd) p := &Poller{epollFd: epollFd} p.closeEvent, err = newEventFd() if err != nil { - unix.Close(epollFd) return nil, err } + defer closeEventFDOnError(p.closeEvent) p.flushEvent, err = newEventFd() if err != nil { - p.closeEvent.close() - unix.Close(epollFd) return nil, err } + defer closeEventFDOnError(p.flushEvent) if err := p.Add(p.closeEvent.raw, 0); err != nil { - unix.Close(epollFd) - p.closeEvent.close() - p.flushEvent.close() return nil, fmt.Errorf("add close eventfd: %w", err) } if err := p.Add(p.flushEvent.raw, 0); err != nil { - unix.Close(epollFd) - p.closeEvent.close() - p.flushEvent.close() return nil, fmt.Errorf("add flush eventfd: %w", err) }