Go and UNIX files

Dan Corin January 6, 2019
Source

I ran into an odd UNIX filename issue while writing Go code the other day.

Here's a simplified example:

Let's read a JSON file and unmarshal its contents into a struct in go. First, let's set an environment variable with our file name to avoid hardcoded constants in our program.

Now, let's read the file into our struct:

Looks like Go couldn't find my file.

The file definitely exists. What about its permissions?

Looks like the file is readable by my program too. So, what is happening?

I can see the file contents too.

I am using the proper path. Let's check that Go is trying to read the correct file path.

Running the code:

The value of the environment variable seems to be correct.

Let's see if we can find any weird characters hiding in the string:

It looks like there is an unexpected space showing up in >/Users/dancorin/Desktop/test.json <. Where is this coming from?

When we set our environment variable, it seems like we accidentally added a trailing space.

Go is trying to tell us this:

It's just not that obvious that there is a space in there. Something like the following could have helped:

UNIX makes this issue a little more confusing because it has no problem allowing you to create filenames with trailing spaces. We can resolve our issue by running

Or, better yet, we can fix our export command:

I hope you never run into this one!

Discussion in the ATmosphere

Loading comments...