Skip to content

Commit 7b96ecb

Browse files
Fixed defer block
1 parent 0701543 commit 7b96ecb

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

migration.go

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ func (m *Migration) LogString() string {
119119

120120
// Buffer buffers Body up to BufferSize.
121121
// Calling this function blocks. Call with goroutine.
122-
func (m *Migration) Buffer() (err error) {
122+
func (m *Migration) Buffer() (berr error) {
123123
if m.Body == nil {
124124
return nil
125125
}
@@ -129,36 +129,33 @@ func (m *Migration) Buffer() (err error) {
129129
b := bufio.NewReaderSize(m.Body, int(m.BufferSize))
130130

131131
// defer closing buffer writer and body.
132-
// defer blocks run in reverse order
133-
134-
// close the Body.
135132
defer func() {
136-
if cerr := m.Body.Close(); cerr != nil {
137-
err = errors.Join(err, cerr)
133+
// close bufferWriter so Buffer knows that there is no
134+
// more data coming.
135+
if err := m.bufferWriter.Close(); err != nil {
136+
berr = errors.Join(berr, err)
138137
}
139-
}()
140138

141-
// always close bufferWriter, even on error, to prevent deadlocks.
142-
// this lets Buffer know that there is no more data coming.
143-
defer func() {
144-
if cerr := m.bufferWriter.Close(); cerr != nil {
145-
err = errors.Join(err, cerr)
139+
// it's safe to close the Body too.
140+
if err := m.Body.Close(); err != nil {
141+
berr = errors.Join(berr, err)
146142
}
143+
147144
}()
148145

149146
// start reading from body, peek won't move the read pointer though
150147
// poor man's solution?
151-
if _, perr := b.Peek(int(m.BufferSize)); perr != nil && perr != io.EOF {
152-
return perr
148+
if _, err := b.Peek(int(m.BufferSize)); err != nil && err != io.EOF {
149+
return err
153150
}
154151

155152
m.FinishedBuffering = time.Now()
156153

157154
// write to bufferWriter, this will block until
158155
// something starts reading from m.Buffer
159-
n, werr := b.WriteTo(m.bufferWriter)
160-
if werr != nil {
161-
return werr
156+
n, err := b.WriteTo(m.bufferWriter)
157+
if err != nil {
158+
return err
162159
}
163160

164161
m.FinishedReading = time.Now()

0 commit comments

Comments
 (0)