Situation:
I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?
What I tried:
I tried using syscall.Read, but it echoes what is typed.
The following is one of best ways to get it done.
First get term package by go get golang.org/x/term
package main
import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "syscall"
    "golang.org/x/term"
)
func main() {
    username, password, _ := credentials()
    fmt.Printf("Username: %s, Password: %s\n", username, password)
}
func credentials() (string, string, error) {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter Username: ")
    username, err := reader.ReadString('\n')
    if err != nil {
        return "", "", err
    }
    fmt.Print("Enter Password: ")
    bytePassword, err := term.ReadPassword(int(syscall.Stdin))
    if err != nil {
        return "", "", err
    }
    password := string(bytePassword)
    return strings.TrimSpace(username), strings.TrimSpace(password), nil
}
http://play.golang.org/p/l-9IP1mrhA
Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass
It something like that:
package main
import "fmt"
import "github.com/howeyc/gopass"
func main() {
    fmt.Printf("Password: ")
    pass := gopass.GetPasswd()
    // Do something with pass
}
                        Since Go ~v1.11 there is an official package golang.org/x/term which replaces the deprecated crypto/ssh/terminal. It has, among other things, the function term.ReadPassword.
Example usage:
package main
import (
    "fmt"
    "os"
    "syscall"
    "golang.org/x/term"
)
func main() {
    fmt.Print("Password: ")
    bytepw, err := term.ReadPassword(int(syscall.Stdin))
    if err != nil {
        os.Exit(1)
    }
    pass := string(bytepw)
    fmt.Printf("\nYou've entered: %q\n", pass)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With