Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Stdin has data with Go

Tags:

stdin

pipe

go

Is there a way to check if the input stream (os.Stdin) has data?

The post Read from initial stdin in GO? shows how to read the data, but unfortunately blocks if no data is piped into the stdin.

like image 757
mauvm Avatar asked Mar 21 '14 16:03

mauvm


2 Answers

os.Stdin is like any other "file", so you can check it's size:

package main

import (
    "fmt"
    "os"
)

func main() {
    file := os.Stdin
    fi, err := file.Stat()
    if err != nil {
        fmt.Println("file.Stat()", err)
    }
    size := fi.Size()
    if size > 0 {
        fmt.Printf("%v bytes available in Stdin\n", size)
    } else {
        fmt.Println("Stdin is empty")
    }
}

I built this as a "pipe" executable, here is how it works:

$ ./pipe
Stdin is empty
$ echo test | ./pipe
5 bytes available in Stdin
like image 76
Kluyg Avatar answered Oct 22 '22 04:10

Kluyg


This seems to be reliable solution and works even with sleep/delayed data via pipe. https://coderwall.com/p/zyxyeg/golang-having-fun-with-os-stdin-and-shell-pipes

package main

import (
  "os"
  "fmt"
)

func main() {
  fi, err := os.Stdin.Stat()
  if err != nil {
    panic(err)
  }
  if fi.Mode() & os.ModeNamedPipe == 0 {
    fmt.Println("no pipe :(")
  } else {
    fmt.Println("hi pipe!")
  }
}
like image 22
PetrD Avatar answered Oct 22 '22 04:10

PetrD