在Go中管道命令时从控制台读取

I need a way to read input from console twice (1 -from cat outupt, 2 - user inputs password), like this: cat ./test_data/test.txt | app account import

My current code skips password input:

reader := bufio.NewReader(os.Stdin)
raw, err := ioutil.ReadAll(reader)
if err != nil {
    return cli.NewExitError(err.Error(), 1)
}

wlt, err := wallet.Deserialize(string(raw))
if err != nil {
    return cli.NewExitError(err.Error(), 1)
}

fmt.Print("Enter password: ")
pass := ""
fmt.Fscanln(reader, &pass)

Also tried to read password with Scanln - doesn't works.

Note: cat (and piping at all) can't be used with user input, as shell redirects inputs totally. So the most simple solutions are:

  • to pass filename as argument

  • redirect manually app account import < ./test.txt

Read file and password separately (and don't show password), try this:

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "github.com/howeyc/gopass"
)

func main() {
    b, err := ioutil.ReadFile("./test_data/test.txt") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }
    fmt.Println(string(b))

    fmt.Print("Password: ")
    pass, err := gopass.GetPasswd()
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(string(pass))
}

and go get github.com/howeyc/gopass first.