duanbangzhou7809 2018-09-24 13:36
浏览 58

如何“推迟” STDIN的阅读

In this minimal working example I'm trying to do the following:

  1. Prompt user for password
  2. Unmarshal JSON either from files specified as arguments or from STDIN

Here's the source code:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "os"
    "syscall"

    "golang.org/x/crypto/ssh/terminal"
)

const correctPassword = "secret"

func main() {
    args := os.Args[1:]

    var passwd string

    for {
        passwd = promptPassword()
        if passwd == correctPassword {
            log.Println("Correct password! Begin processing...")
            break
        }
        log.Println("Incorrect password!")
    }

    if len(args) == 0 { // Read from stdin
        log.Println("Reading from stdin")
        dec := json.NewDecoder(os.Stdin)
        for {
            var v interface{}
            if err := dec.Decode(&v); err == io.EOF {
                break
            } else if err != nil {
                log.Fatal(err)
            }
            log.Printf("%#v", v)
        }
    }

    for _, fileName := range args {
        log.Println("Reading from", fileName)
        f, err := os.Open(fileName)
        if err != nil {
            log.Println(err)
            continue
        }
        defer f.Close()
        dec := json.NewDecoder(f)
        for {
            var v interface{}
            if err := dec.Decode(&v); err == io.EOF {
                break
            } else if err != nil {
                log.Fatal(err)
            }
            log.Printf("%#v", v)
        }
    }
}

func promptPassword() (passwd string) {
    for {
        fmt.Fprintln(os.Stderr, "Enter password:")
        b, _ := terminal.ReadPassword(int(syscall.Stdin))
        passwd = string(b)
        if passwd != "" {
            break
        }
    }
    return passwd
}

Everything works all right except when already prepared data is piped or redirected (e.g. go run main.go < mydata.json, or echo 42 | go run main.go, etc).

When I pipe or redirect some data to the program, the data gets processed by the password prompt, not the JSON decoder part. Is there any way to at first prompt for the password, and only after process the incoming data?

I was trying to detect if there's any data in STDIN to read it and store in some temporary bytes slice, but I can't find how to close/truncate the STDIN, so it won't read data twice.

  • 写回答

2条回答 默认 最新

  • doufan9805 2018-09-24 19:21
    关注

    You wont be able because the shell will close the stdin file descriptor once it has finished to write the content.

    Once stdin is closed you cant re open it, this is controlled by the shell.

    Check this program, to test this behavior

    package main
    
    import (
        "fmt"
        "io"
        "os"
    )
    
    func main() {
        io.Copy(os.Stdout, os.Stdin)
        fmt.Println("done")
        some := make([]byte, 100)
        _, err := os.Stdin.Read(some)
        fmt.Println(err)
        fmt.Println(string(some))
    }
    

    The output will be

    $ echo "some" | go run main.go 
    some
    done
    EOF
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。