This commit is contained in:
57
main.go
57
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")
|
||||
}
|
||||
fmt.Print("Pokedex > ")
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user