Home  >  Article  >  Backend Development  >  How to Input User Credentials into an External Program via Stdin in Go?

How to Input User Credentials into an External Program via Stdin in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 01:28:30815browse

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:

  1. Create a bytes.Buffer and write the username and password, separated by newline characters.
  2. Assign the buffer to the command's Stdin field.
  3. Execute the command as usual, redirecting its stdout and stderr to your program.

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!

Statement:
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