July 2019
Intermediate to advanced
458 pages
12h 12m
English
Now that everything is set, it only remains to define what the various commands will actually do. We can define the type of the function that executes a command and how the switch behaves:
var cmdFunc func(w io.Writer, args []string) (exit bool)switch cmd {case "exit": cmdFunc = exitCmd}if cmdFunc == nil { fmt.Fprintf(w, "%q not found\n", cmd) continue}if cmdFunc(w, args) { // execute and exit if true return}
The return value tells the application whether it needs to terminate or not and allows us to define our exit function easily, without it being a special case:
func exitCmd(w io.Writer, args []string) bool { fmt.Fprintf(w, "Goodbye! :)") return true}
We could implement any type of command now, depending on the scope ...
Read now
Unlock full access