Check if there is something to read on STDIN in Golang

后端 未结 4 1816
天涯浪人
天涯浪人 2020-12-08 02:55

I need a command line utility to behave different if some string is piped into its STDIN. Here\'s some minimal example:

package main // file test.go

import          


        
4条回答
  •  春和景丽
    2020-12-08 03:36

    If none of the above works for you, try this way:

    stat, err := os.Stdin.Stat()
    if err != nil {
        return nil, fmt.Errorf("you have an error in stdin:%s", err)
    }
    if (stat.Mode() & os.ModeNamedPipe) == 0 {
        return nil, errors.New("you should pass smth to stdin")
    }
    

    It worked for me in both darwin (Mac OS) and linux (Ubuntu).

提交回复
热议问题