Skip to content

Commit

Permalink
🎨 Add some stdin reading tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wesen committed Sep 21, 2023
1 parent 2e3bf4e commit 4006236
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions cmd/stdin-reading/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package main

import (
"bufio"
"fmt"
"io/ioutil"
"os"
)

func main() {
// Reading piped data (if any)
pipedData, _ := ioutil.ReadAll(os.Stdin)
fmt.Printf("Received piped data: %s\n", pipedData)

// Now, we want to read user input from the terminal

// Open the terminal for reading
tty, err := os.Open("/dev/tty")
if err != nil {
fmt.Println("Failed to open terminal:", err)
return
}
defer func(tty *os.File) {
_ = tty.Close()
}(tty)

reader := bufio.NewReader(tty)

for {
// Ask the user if they want to continue
fmt.Print("Do you want to continue in chat? [y/n]: ")

input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Failed to read input:", err)
return
}

switch input[0] {
case 'y', 'Y':
chat()
case 'n', 'N':
return
default:
fmt.Println("Invalid input. Please enter 'y' or 'n'.")
}
}
}

func chat() {
fmt.Println("You're now in chat! (For the sake of this example, we'll simply return to the main loop after this message.)")
}

0 comments on commit 4006236

Please sign in to comment.