DEV Community

Adil 🧩
Adil 🧩

Posted on

Implementing a 'radio button' in Golang shell program

I came across this question in the Gopher slack channel and I thought I might have a crack at answering it. Gopher newbie, so as always C&C welcome and appreciated!

@J so you want to prompt with a question first. The code for this is pretty simple;

reader := bufio.NewReader(os.Stdin)
fmt.Print("? How would you like to use ESLint??")

Now the next part is a bit ambigious, because while you mention radio button like behaviour, the screen shot you supplied is actually a selector that you navigate by using the directional keys. If it were an actual radio button, you could simply attach a value to each of the options, and then execute the code you want depending on the answer. For example

? How would you like to use ESLint?
> To check syntax only (1)
> To check syntax and find problems (2)
> To check syntax, find problems, and  enforce code style (3)
$ > 3
! You have selected the syntax only mode

To implement this would be pretty simple too.

reader := bufio.NewReader(os.Stdin)
fmt.Print("? How would you like to use ESLint??")
fmt.Print("To check syntax only (1) ")
fmt.Print("To check syntax and find problems (2) ")
fmt.Print("To check syntax, find problems, and enforce code style (3) ")

answer, _ := reader.ReadString('\n') // Allow user input up until and including \n
answer = strings.TrimSuffix(answer, "\n") // Remove trailing \n from string
if answer == "1" {
  // check syntax code execution
} else if answer == "2" {
  // check syntax and find problems code execution
} else if answer == "3" {
  // check syntax find problems and enfore style code code execution
} else {
  fmt.Print("Answer isn't recognised")
  // start again
}

I would probably use a switch statement to make it a little more cleaner too, and also wrap the question printing and answer gathering into a function that would be called when the answer isn't recognized. but then again, there's quite a bit of refactoring that you could do.

If you wish to implement the selector behaviour, where you can navigate the options with the directional keys, it would be more complex (I'd imagine). You'd have to find a way to;

  1. Print multiple lines that can be navigated
  2. Allow user to navigate the lines (probably by using the same method as above, but triggering navigation when the arrow keys are pressed)
  3. Highlight the line currently being selected
  4. Run behaviour based on selected option when the enter key is pressed.

Personally, I feel like that's a lot of work for not much gain in UX, but it definitely is possible in Go, as are all things if you put your mind to it!

Top comments (0)