From bea73f0115080132ceebef53fcf0ff086c07aa94 Mon Sep 17 00:00:00 2001 From: Darius Rapalis Date: Mon, 10 Mar 2025 22:00:05 +0200 Subject: [PATCH] #4 --- main.go | 55 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 006ecf2..f46e80f 100644 --- a/main.go +++ b/main.go @@ -7,28 +7,55 @@ import ( "strings" ) +type cliCommand struct { + name string + description string + callback func() error +} + +var commands map[string]cliCommand + func main() { - - quit := false - - for !quit { - + commands = map[string]cliCommand{ + "exit": { + name: "exit", + description: "Exit the Pokedex", + callback: commandExit, + }, + "help": { + name: "help", + description: "Display a help message", + callback: printHelpMessage, + }, + } + for { // read user input input := bufio.NewScanner(os.Stdin) fmt.Print("Pokedex > ") for input.Scan() { word := input.Text() cleanedWord := cleanInput(word) - fmt.Printf("Your command was: %s\n", cleanedWord[0]) + command := cleanedWord[0] - if cleanedWord[0] == "quit" { - quit = true + //check if command is in commands map + cmd, ok := commands[command] + if ok { + err := cmd.callback() + if err != nil { + fmt.Println(err) + } + } else { + fmt.Println("Unknown command") } - break + fmt.Print("Pokedex > ") } - } +} +func commandExit() error { + fmt.Println("Closing the Pokedex... Goodbye!") + os.Exit(0) + return nil } func cleanInput(text string) []string { @@ -42,3 +69,11 @@ func cleanInput(text string) []string { separated := strings.Split(text, " ") return separated } + +func printHelpMessage() error { + fmt.Print("Welcome to the Pokedex!\nUsage:\n\n") + for k, v := range commands { + fmt.Printf("%s: %s\n", k, v.description) + } + return nil +}