Golang : Handling Yes No Quit query input
The following is a simple program that will accept a single key answer from the console without the user hitting the Enter
button and check if the answer is valid or not. Basically what it does is to prompt the user with a question and expect the user to answer Yes, No or Quit. Useful in situation where your program needs the user to give permission or customize/install certain modules.
Here you go!
package main
/*
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
char getch(){
char ch = 0;
struct termios old = {0};
fflush(stdout);
if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if( tcsetattr(0, TCSANOW, &old) < 0 ) perror("tcsetattr ICANON");
if( read(0, &ch,1) < 0 ) perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if(tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr ~ICANON");
return ch;
}
*/
import "C"
// stackoverflow.com/questions/14094190/golang-function-similar-to-getchar
import (
"fmt"
"math/rand" // to randomize the questions
"os"
"strings"
"time"
)
func main() {
validAnswers := map[string]string{"y": "yes", "n": "no", "q": "quit"}
questions := []string{"Do you want to make peace with the rest of the world?", "Terminate evil artificial intelligence program?", "Do you believe in a future that robot help us unconditionally?", "Promise to be a good boy?", "Spank them?"}
prompt := "[Yes/No/Quit]"
rand.Seed(time.Now().UnixNano())
for {
fmt.Println(questions[rand.Intn(len(questions))] + " " + prompt)
// get a single character from keyboard with hitting Enter button
// if you need your user to hit the Enter key
// see https://www.socketloop.com/tutorials/golang-get-input-from-keyboard
char := C.getch()
// convert type C.char to Golang string type
answer := fmt.Sprintf("%c", char)
answer = strings.ToLower(answer)
if validAnswers[answer] == "" {
fmt.Println("Please respond with y, n or q")
} else {
fmt.Println("Your answer is : ", validAnswers[answer])
}
if answer == "q" {
fmt.Println("Bye!")
os.Exit(0)
}
}
}
Sample output:
Spank them? [Yes/No/Quit]
Your answer is : yes
Do you believe in a future that robot help us unconditionally? [Yes/No/Quit]
Your answer is : no
Do you believe in a future that robot help us unconditionally? [Yes/No/Quit]
Your answer is : quit
Bye!
Do you want to make peace with the rest of the world? [Yes/No/Quit]
Your answer is : yes
Terminate evil artificial intelligence program? [Yes/No/Quit]
Your answer is : yes
Do you believe in a future that robot help us unconditionally? [Yes/No/Quit]
Your answer is : yes
Do you want to make peace with the rest of the world? [Yes/No/Quit]
Your answer is : yes
Do you want to make peace with the rest of the world? [Yes/No/Quit]
Your answer is : yes
Terminate evil artificial intelligence program? [Yes/No/Quit]
Your answer is : yes
Do you want to make peace with the rest of the world? [Yes/No/Quit]
Your answer is : yes
Promise to be a good boy? [Yes/No/Quit]
Your answer is : no
Terminate evil artificial intelligence program? [Yes/No/Quit]
Your answer is : quit
Bye!
References:
https://www.socketloop.com/tutorials/golang-check-if-element-exist-in-map
https://www.socketloop.com/tutorials/golang-randomly-pick-an-item-from-a-slice-array-example
https://www.socketloop.com/tutorials/golang-get-input-from-keyboard
See also : Golang : Get input from keyboard
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.2k Golang : Convert file unix timestamp to UTC time example
+5.9k Linux/MacOSX : Search for files by filename and extension with find command
+13.7k Golang : Gin framework accept query string by post request example
+19.3k Golang : Fix cannot download, $GOPATH not set error
+12.3k Golang : Extract part of string with regular expression
+41k Golang : How to count duplicate items in slice/array?
+5k Golang : Display packages names during compilation
+21.8k Golang : Use TLS version 1.2 and enforce server security configuration over client
+18.4k Golang : Aligning strings to right, left and center with fill example
+9.2k Golang : How to get ECDSA curve and parameters data?
+11.1k Golang : Fix - does not implement sort.Interface (missing Len method)
+7.7k Golang : Getting Echo framework StartAutoTLS to work