Commit bd9df9c
Changed files (1)
command.go
@@ -0,0 +1,94 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// Command stores the information for running a command
+type Command struct {
+ Command string
+ Description string
+ Run func(args []string) error
+}
+
+// selectCommand takes a string and converts it to the correct command
+func selectCommand(str string) (Command, error) {
+ for _, value := range commandArray {
+ if strings.Compare(value.Command, str) == 0 {
+ return value, nil
+ }
+ }
+ return Command{}, fmt.Errorf("No command found for: %s", str)
+}
+
+// commandArray contains the full list of commands available to the application
+// note that subcommands are not currently supported
+var commandArray = []Command{Command{Command: "test",
+ Description: "Execute a test. Given a number, will go through a test with [n] questions. Type 'exit' to stop test.",
+ Run: executeTest},
+ Command{Command: "score",
+ Description: "Display the score for the user.",
+ Run: func(args []string) error {
+ fmt.Print("score was run.")
+ return nil
+ }},
+ Command{Command: "exit",
+ Description: "Exit the self-assessment application and close the connection.",
+ Run: func(args []string) error {
+ fmt.Print("Exiting application.\n")
+ os.Exit(0)
+ return nil
+ }}}
+
+// helpCommand prints the help for the list of available commands.
+// it cannot exist in the initialization due to initialization loops
+var helpCommand = Command{Command: "help",
+ Description: "Display help for all known commands.",
+ Run: func(args []string) error {
+ for _, command := range commandArray {
+ fmt.Printf("%s\n\t%s\n", command.Command, command.Description)
+ }
+ return nil
+ }}
+
+// init initializes the commandArray to provide a single interface
+func init() {
+ commandArray = append(commandArray, helpCommand)
+}
+
+// executeTest runs a user through a test
+func executeTest(args []string) error {
+ client := &http.Client{}
+ var record Record
+ var err error
+ var input string
+ questions := 20
+ if len(args) > 0 {
+ questions, err = strconv.Atoi(args[0])
+ if err != nil {
+ return fmt.Errorf("Error while converting to number: %+v", err)
+ }
+ }
+ reader := bufio.NewReader(os.Stdin)
+ for i := 0; i < questions; i += 1 {
+ record, err = getRecordFromServer(client, config)
+ if err != nil {
+ return fmt.Errorf("Error while request from server: %+v", err)
+ }
+ fmt.Printf("%d) %s\n", i+1, record.Question)
+ input, _ = reader.ReadString('\n')
+ if strings.Compare(strings.TrimSpace(input), record.Answer) == 0 {
+ fmt.Println("Correct.")
+ } else if strings.Compare(strings.TrimSpace(input), "exit") == 0 {
+ return nil
+ } else {
+ fmt.Printf("Incorrect. Correct answer was: %s\n", record.Answer)
+ }
+ }
+ return nil
+}