go - 检查 Golang 中的 STDIN 是否有需要阅读的内容

标签 go

如果某些字符串通过管道传输到其 STDIN,我需要一个命令行实用程序来表现不同。这是一些最小的例子:

package main // file test.go

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    bytes, _ := ioutil.ReadAll(os.Stdin)

    if len(bytes) > 0 {
        fmt.Println("Something on STDIN: " + string(bytes))
    } else {
        fmt.Println("Nothing on STDIN")
    }
}

如果你这样调用它就可以了:

echo foo | go run test.go

如果在 STDIN 上没有任何内容就调用 test.go,那么事情就会卡在...

bytes, _ := ioutil.ReadAll(os.Stdin)

...等待EOF

我需要做什么才能让这一切顺利进行?

提前致谢!

最佳答案

我通过使用 os.ModeCharDevice 解决了这个问题:

stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
    fmt.Println("data is being piped to stdin")
} else {
    fmt.Println("stdin is from a terminal")
}

关于go - 检查 Golang 中的 STDIN 是否有需要阅读的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744443/

相关文章:

go - Golang模式可一次杀死多个goroutine

go - 响应没有实现 http.Hijacker

Git repo inside git repo, 由 go get 创建 - convert to submodule

golang 1.12导入相对目录模块

从函数和调用者到终端的 Golang 错误处理

types - Go中函数变量的类型

postgresql - 单元测试 Postgres 数据库连接 golang

go - 在 : panic: runtime error: index out of range 中转换数据结构

GO编程,在阅读器事件上阻止读取功能

go - 获取 GO 语言的包