Home > Backend Development > Golang > How to Implement Non-Echoing Password Entry in Go?

How to Implement Non-Echoing Password Entry in Go?

Linda Hamilton
Release: 2024-12-29 17:03:10
Original
757 people have browsed it

How to Implement Non-Echoing Password Entry in Go?

Non-Echoing Password Entry in Go

Situation:

Retrieving a password from the user without displaying the entered characters is a common requirement. How can this be achieved in Go?

Solution:

Go does not directly offer a getpasswd functionality. However, the following approach effectively accomplishes the task:

Implementation Details

  1. Disable Echo: To suppress character echo, the term package is imported. term.ReadPassword is utilized to read the password while concealing user input.
  2. Get Username: The script prompts the user for a username using fmt.Print. The bufio.NewReader is used to read the username.
  3. Get Password: term.ReadPassword is used to obtain the password after prompting the user for it. Passwords entered by the user are not visible in the console.
  4. Trim Whitespace: The obtained username and password are trimmed to remove any leading or trailing whitespace.

Example:

package main

import (
    "bufio"
    "fmt"
    "golang.org/x/term"
    "os"
    "strings"
)

func main() {
    u, p, _ := credentials()
    fmt.Printf("Username: %s, Password: %s\n", u, p)
}

func credentials() (string, string, error) {
    fmt.Print("Enter Username: ")
    r := bufio.NewReader(os.Stdin)
    u, err := r.ReadString('\n')
    if err != nil {
        return "", "", err
    }

    fmt.Print("Enter Password: ")
    bp, err := term.ReadPassword(int(syscall.Stdin))
    if err != nil {
        return "", "", err
    }

    p := string(bp)
    return strings.TrimSpace(u), strings.TrimSpace(p), nil
}
Copy after login

This code snippet demonstrates the process of obtaining username and password from the user without displaying the password characters.

The above is the detailed content of How to Implement Non-Echoing Password Entry in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template