I am having some difficulties cancelling my program with Ctrl+C. I believe my knowledge of channels must be a bit off as I can't wrap my head around why this program won't close with Ctrl+C when it prompts for the password.
Would anyone be able to say why it won't exit after asking for the "Password" and pressing Ctrl+C?
package main
import (
"fmt"
"os"
"os/user"
"os/signal"
"syscall"
"github.com/howeyc/gopass"
)
func main() {
signalChannel := make(chan os.Signal, 2)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGINT)
go func() {
sig := <-signalChannel
switch sig {
case os.Interrupt:
os.Exit(0)
case syscall.SIGINT:
os.Exit(0)
}
}()
user, _ := user.Current()
fmt.Printf("Hi %s, password please: ", user.Username)
pass := gopass.GetPasswd()
fmt.Printf("Recieved as: %s
", pass)
}
Any help is appreciated, thanks.
Update
I resolved this by switching to https://github.com/seehuhn/password which listens for signals
Ctrl-C
is SIGINT. Ctrl-\
is SIGQUIT (by default). You will want to change the signal your application listens for.
This answer has some further details on the typical (but some implementations may stray) shortcuts for signals in a terminal: https://superuser.com/a/343046/93194
Update: gopass is interfering with your signal handling. Look at using http://godoc.org/code.google.com/p/go.crypto/ssh/terminal#ReadPassword instead:
state, err := terminal.MakeRaw(0)
if err != nil {
log.Fatal(err)
}
defer terminal.Restore(0, state)
term := terminal.NewTerminal(os.Stdout, ">")
password, err := term.ReadPassword("Enter password: ")
if err != nil {
log.Fatal(err)
}