To implement a simple command-line interface (CLI) using bufio in Go, you can follow these steps:
import (
"bufio"
"fmt"
"os"
"strings"
)
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")
}
}
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
handleCommand(input)
}
}
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.