Providing a basic implementation of Ruby's in Go

Featured image for sharing metadata for article

While I write more Go command-line utilities, I find that I'm generally reading from stdin, but sometimes need to read input from files.

I was happy using file redirection in my shell, for instance:

$ ./helper <<< stdin
$ ./helper < file.txt

As a lot of my scripts are using Ruby, as a better alternative to Bash scripting, I learned that is a great alternative to this, where instead of the user of a script needing to invoke based on whether they were using a file or stdin, we can instead read from either much more easily.

For instance:

$ ruby -e 'puts' <<< "this is stdin"
this is stdin
$ ruby -e 'puts' file.txt
This is from a file
$ ruby -e 'puts' file.txt - <<< "this is stdin"
This is from a file
this is stdin

Although can do a lot more, I generally use it for a single file.

As I'm writing a lot more Go at the moment, I wanted something similar, so I've come up with the following method to read from stdin or a file on the command-line arguments if present:

func ArgfRead() (string, error) {
	var bytes []byte
	var err error

	if len(os.Args) >= 2 {
		bytes, err = os.ReadFile(os.Args[1])
	} else {
		bytes, err = io.ReadAll(os.Stdin)

	if err != nil {
		return "", err
	return strings.TrimSuffix(string(bytes), "\n"), nil

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 #ruby.

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.