The smallest pipeable go program

e · l · n
Dec 18, 2014

Edit: My original suggested way further below in the post is no way the "smallest pipeable" program, instead see this example (Credits: Axel Wagner):

package main

import (
    "io"
    "os"
)

func main() {
    io.Copy(os.Stdout, os.Stdin)
}

... or (credits: Roger Peppe):

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    for scan := bufio.NewScanner(os.Stdin); scan.Scan(); {
        fmt.Printf("%s\n", scan.Text())
    }
}

Ah, I just realized that the "smallest pipeable" Go(lang) program is rather small, if using my little library of minimalistic streaming components. Nothing more than:

package main

import (
    "fmt"
    "github.com/samuell/glow"
)

func main() {
    inchan := make(chan []byte, 16)
    glow.NewStdInReader(inchan)
    for line := range inchan {
        fmt.Println(string(line))
    }
}

Naturally, you would want ot fill in the doSomething() function with something more fancy.

But then, you can pipe any output through the program, and it will process the input (in this case just forward it):

[samuel glowtest]$ go build glowtest.go 
[samuel glowtest]$ ls -l | ./glowtest 
total 2,0M
-rwxrwxr-x 1 samuel samuel 2,0M dec 18 19:04 glowtest
-rw-rw-r-- 1 samuel samuel  291 dec 18 19:03 glowtest.go