Skip to content

Commit 8ffac0e

Browse files
Marcel Hermnexoscp
authored andcommitted
Improve error handling, refactor loop, add context to FollowTail
1 parent 55adede commit 8ffac0e

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

sdjournal/read.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@
1616
package sdjournal
1717

1818
import (
19+
"context"
1920
"errors"
2021
"fmt"
2122
"io"
2223
"log"
24+
"strconv"
2325
"strings"
2426
"sync"
2527
"time"
@@ -258,24 +260,35 @@ process:
258260

259261
// SkipN skips the next n entries and returns the number of skipped entries and an eventual error.
260262
func (r *JournalReader) SkipN(n int) (int, error) {
263+
if n < 0 {
264+
return -1, errors.New("can not skip by negative number " + strconv.Itoa(n))
265+
}
261266
var i int
262-
for i := 1; i <= n; i++ {
267+
for i < n {
263268
c, err := r.journal.Next()
264269
if err != nil {
265270
return i, err
266271
} else if c == 0 {
267272
return i, nil
268273
}
274+
i += 1
269275
}
270276
return i, nil
271277
}
272278

273279
// FollowTail synchronously follows the JournalReader, writing each new journal entry to entries.
274280
// It will start from the next unread entry.
275-
func (r *JournalReader) FollowTail(entries chan *JournalEntry) error {
281+
func (r *JournalReader) FollowTail(entries chan *JournalEntry, ctx context.Context) error {
276282
defer close(entries)
277283

278284
for {
285+
select {
286+
case <-ctx.Done():
287+
fmt.Println("Context done, exit FollowTail")
288+
return nil
289+
default:
290+
}
291+
279292
status := r.journal.Wait(200 * time.Millisecond)
280293
if status != SD_JOURNAL_APPEND && status != SD_JOURNAL_INVALIDATE {
281294
continue

0 commit comments

Comments
 (0)