Input management

The standard input can be used to receive user commands. We can start by using a buffered input to read lines and print them. In order to read a line, there is a useful command, bufio.Scanner, that already provides a line reader. The code will look similar to the following code snippet:

s := bufio.NewScanner(os.Stdin)
w := os.Stdout
fmt.Fprint(w, "Some welcome message ")
for {
s.Scan() // get next the token
fmt.Fprint(w, "You wrote "")
w.Write(s.Bytes())
fmt.Fprintln(w, "" ") // writing back the text
}

Since this code has no exit point, we can start by creating the first command, exit, that will terminate the shell execution. We can do a small change in the code to make this work, as shown in the following:

s := bufio.NewScanner(os.Stdin)
w := os.Stdout
fmt.Fprint(w, "Some welcome message ")
for {
s.Scan() // get next the token
msg := string(s.Bytes())
if msg == "exit" {
return
}
fmt.Fprintf (w, "You wrote %q ", msg) // writing back the text
}

Now the application has an exit point other than the kill command. For now, it does not implement any command, besides the exit one, and all it does is print back whatever you type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.214.155