Skip to content

Commit

Permalink
(fix): allow input via stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
kameshsampath committed Apr 8, 2024
1 parent 824c587 commit a2e140c
Showing 1 changed file with 39 additions and 20 deletions.
59 changes: 39 additions & 20 deletions cmd/add/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"bufio"
"context"
"flag"
"log"
"os"
"os/signal"

"github.com/kameshsampath/demo-protos/golang/todo"
"go.uber.org/zap"
Expand All @@ -14,51 +14,70 @@ import (
"google.golang.org/protobuf/encoding/protojson"
)

var log *zap.SugaredLogger

func init() {
logger, _ := zap.NewDevelopment()
defer logger.Sync()
log = logger.Sugar()
}

func main() {
var scanner *bufio.Scanner
var stdin bool
var dbFile string
flag.BoolVar(&stdin, "stdin", false, "app -stdin")
flag.StringVar(&dbFile, "d", "data/todos.jsonl", "app -d ./todos.jsonl")
flag.Parse()

if _, err := os.Stat(dbFile); err != nil && os.IsNotExist(err) {
log.Fatalf("data file %s not found.", dbFile)
}

logger, _ := zap.NewDevelopment()
defer logger.Sync()
log := logger.Sugar()

conn, err := grpc.Dial(os.Getenv("SERVICE_ADDRESS"), grpc.WithTransportCredentials(insecure.NewCredentials()))

if err != nil {
log.Fatal(err)
}
defer conn.Close()

file, err := os.Open(dbFile)
if err != nil {
log.Fatal(err)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

if stdin {
log.Infoln("Enter Todo Task JSON to send, press CTRL+C to quit")
scanner = bufio.NewScanner(os.Stdin)
go scanAndSend(ctx, conn, scanner)
<-ctx.Done()
} else {
if _, err := os.Stat(dbFile); err != nil && os.IsNotExist(err) {
log.Fatalf("data file %s not found.", dbFile)
}
file, err := os.Open(dbFile)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner = bufio.NewScanner(file)
scanAndSend(ctx, conn, scanner)
}
defer file.Close()
scanner := bufio.NewScanner(file)

}

func scanAndSend(ctx context.Context, conn *grpc.ClientConn, scanner *bufio.Scanner) {
for scanner.Scan() {
line := scanner.Text()
task := new(todo.Task)
if err := protojson.Unmarshal([]byte(line), task); err != nil {
log.Errorf("error processing record, %s: %s", line, err)
continue
}

client := todo.NewTodoClient(conn)
_, err = client.AddTodo(
context.Background(),
&todo.TodoAddRequest{Task: task},
)
_, err := client.AddTodo(ctx, &todo.TodoAddRequest{Task: task})
if err != nil {
log.Fatal(err)
log.Errorf("error adding record, %s: %s", line, err)
continue
}

if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}

}

0 comments on commit a2e140c

Please sign in to comment.