How to implement a simple command-line interface (CLI) using bufio in Go?

To implement a simple command-line interface (CLI) using bufio in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "bufio" "fmt" "os" "strings" )
  1. Create a function to handle user input and processing commands:
func handleCommand(command string) { // Process the command here // Example: if command == "hello" { fmt.Println("Hello!") } else if command == "exit" { os.Exit(0) } else { fmt.Println("Invalid command") } }
  1. Create a loop to continuously read user input and call the command handler function:
func main() { reader := bufio.NewReader(os.Stdin) for { fmt.Print("> ") input, _ := reader.ReadString('\n') input = strings.TrimSpace(input) handleCommand(input) } }
  1. Run the program and test the CLI:
go run main.go

Now, you can type commands in the terminal and see the output based on the command.

Example Usage:

> hello Hello! > invalid Invalid command > exit

Note: This is a basic implementation that reads input until the user enters "exit". You can extend it to perform more complex operations based on different commands.