Home > Article > Backend Development > How to Input User Credentials into an External Program via Stdin in Go?
Inputting User Credentials into External Program via stdin
Consider the scenario where you wish to execute an external command and provide user credentials from within a Go program. The command prompts for username and password inputs in separate fields. Determining how to sequentially fill these fields using stdin can be a challenge.
Solution: Utilizing a bytes.Buffer
To address this, utilize the bytes.Buffer type, which enables the creation of a buffer for writing and reading byte data. Follow these steps:
Example code:
<code class="go">login := exec.Command(cmd, "login") var b bytes.Buffer b.Write([]byte(username + "\n" + pwd + "\n")) login.Stdout = os.Stdout login.Stdin = &b login.Stderr = os.Stderr err := login.Run() if err != nil { fmt.Fprintln(os.Stderr, err) }</code>
This approach takes advantage of the fact that stdin reads characters until encountering a newline. By feeding the buffer to stdin, the command will read the credentials sequentially without encountering any ambiguity.
The above is the detailed content of How to Input User Credentials into an External Program via Stdin in Go?. For more information, please follow other related articles on the PHP Chinese website!