Skip to content

Commit e94dd35

Browse files
committed
add --follow / -f flag to start consuming from HEAD-1 offset
1 parent b66ee6c commit e94dd35

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

cmd/kaf/consume.go

+26-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
"os"
56
"sync"
67

78
"github.com/birdayz/sarama"
@@ -11,13 +12,15 @@ import (
1112

1213
var (
1314
offsetFlag string
14-
prettyPrint bool
15+
raw bool
16+
follow bool
1517
)
1618

1719
func init() {
1820
rootCmd.AddCommand(consumeCmd)
1921
consumeCmd.Flags().StringVar(&offsetFlag, "offset", "oldest", "Offset to start consuming. Possible values: oldest, newest. Default: newest")
20-
consumeCmd.Flags().BoolVar(&prettyPrint, "pretty", false, "Pretty print output if possible, e.g. for JSON.")
22+
consumeCmd.Flags().BoolVar(&raw, "raw", false, "Print raw output of messages, without key or prettified JSON")
23+
consumeCmd.Flags().BoolVarP(&follow, "follow", "f", false, "Shorthand to start consuming with offset HEAD-1 on each partition. Overrides --offset flag")
2124
}
2225

2326
var consumeCmd = &cobra.Command{
@@ -61,6 +64,25 @@ var consumeCmd = &cobra.Command{
6164
wg.Add(1)
6265

6366
go func(partition int32) {
67+
req := &sarama.OffsetRequest{
68+
Version: int16(1),
69+
}
70+
req.AddBlock(topic, partition, int64(-1), int32(0))
71+
ldr, err := client.Leader(topic, partition)
72+
if err != nil {
73+
panic(err)
74+
}
75+
offsets, err := ldr.GetAvailableOffsets(req)
76+
if err != nil {
77+
panic(err)
78+
}
79+
followOffset := offsets.GetBlock(topic, partition).Offset - 1
80+
81+
if follow && followOffset > 0 {
82+
offset = followOffset
83+
fmt.Fprintf(os.Stderr, "Starting on partition %v with offet %v\n", partition, offset)
84+
}
85+
6486
pc, err := consumer.ConsumePartition(topic, partition, offset)
6587
if err != nil {
6688
panic(err)
@@ -70,14 +92,14 @@ var consumeCmd = &cobra.Command{
7092

7193
dataToDisplay := msg.Value
7294

73-
if prettyPrint {
95+
if !raw {
7496
formatted, err := prettyjson.Format(msg.Value)
7597
if err == nil {
7698
dataToDisplay = formatted
7799
}
78100
}
79101

80-
if msg.Key != nil && len(msg.Key) > 0 {
102+
if msg.Key != nil && len(msg.Key) > 0 && !raw {
81103
fmt.Printf("%v %v\n", string(msg.Key), string(dataToDisplay))
82104
} else {
83105
fmt.Printf("%v\n", string(dataToDisplay))

0 commit comments

Comments
 (0)