Reading all of stdin on the command-line with Go

Featured image for sharing metadata for article

If you're writing command-line tools with Go, you're very likely to want to parse all of stdin, from the first byte, up until the End of File character (EOF).

For instance, you may be receiving input from various means:

# piping from a file
go run main.go < file.txt

# piping with a heredoc
go run main.go <<< EOF
Multi-line
heredoc
EOF

# useless use of cat, but example of piping a command
cat file.txt | go run main.go

# writing the text to stdin
go run main.go
example
text
^D

To read this, in its entirety, we can use io.ReadAll like so:

package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func main() {
	// this does all the work for us!
	stdin, err := io.ReadAll(os.Stdin)

	if err != nil {
		panic(err)
	}
	str := string(stdin)

	fmt.Println(strings.TrimSuffix(str, "\n"))
}

As noted above, this comment from 2018 noting that you stdin doesn't close no longer seems to be the case, at least in the test I performed on go version go1.17.7 linux/amd64.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go #command-line.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.