Then I would stick to my first comment. I would explain a little more.
You don't need a signal to have your program terminate - you have control over it. Call os.Exit
at any time would exit the program, and return from main()
has the same effect.
The problem is, instead, that when to trigger these "exits". Or, in your example, how to trigger the exit when the key Q
is pressed.
To solve the problem, you need to break it down into parts. As I said in the comments, the part 1 is capturing the key stroke. It is not as simple as an fmt.Scan
, as it would require the user press an enter after it. It requires some os specific code to do so, but hopefully a lib can save you all the trouble, like termbox-go.
The part 2 is tightly associated with part 1. That is to specify the event, the key stroke. In your example, to know the key pressed is Q, and then call os.Exit
. Usually a lib can handle that pretty easily, sometimes one can hardly notice there is a part. But if you want some more complicated key stokes, like ctrl-alt-backspace
, or even a-s-d-f
(at the same time), this will require some codes.
The 3rd part is about not blocking the program. In Go, it can easily be acheived by using a seperate goroutine to check an event loop, or use the good-old callback way. It is up to library you pick.
A little more about signal and the ctrl-c
case. It is common practice that ctrl-c
is bound to send a sigint to the program, in most situations. And if not modified, a sigint terminates a program. However, a program can modify the behavior of dealing with sigint, like your orignal code does (adds a message to print). When pressing other keys, it is unlikely the os would bind it to another signal, so you can not deal with it.
Of corse another solution would be bind a key compostion (multiple key strokes) to sending a sigint to the program, but as long as the program is the program receiving the key stroke itself, that is a redunctant.
Note: Because of the choice of libs can be varied, the codes are very much differed, so I don't think I can (or should) provide an example.