Redirecting stdout to /dev/null in Go

Yesterday was the six month anniversary since I started my new job.  It’s been busy and I’ve learned a lot.  One thing I had to start learning was the Go programming language (aka Golang).  Today I wanted to temporarily suppress the standard out, but searching the Internet didn’t come up with any concise solutions.  What I did was pretty simple, but seems to work.

Basically, I’m using a third party package to parse an ini file.  The code works fine, but it is very verbose and prints out several lines of information that end up cluttering my logs.  My solution was to simply redirect the standard out to /dev/null.  Here’s what my code ended up looking like:

func unmarshal(bytes []byte, info *InfoStruct) error {

    // Redirect standard out to null
    stdout := os.Stdout
    defer func() { os.Stdout = stdout }()
    os.Stdout = os.NewFile(0, os.DevNull)

    return ini.Unmarshal(bytes, info)
}

Hopefully the code is easy to follow.  The “InfoStruct” is just some struct for data that is in the ini file.  The “ini” prefix is for the third party package that I am using.

In my quick searching, I found various information about redirecting logs, redirecting command output, etc.  There were even some examples of redirecting the stdout, but none were exactly what I wanted and most were less concise.

 

Author: Nathan

I like to do stuff.

One thought on “Redirecting stdout to /dev/null in Go”

Leave a Reply

Your email address will not be published. Required fields are marked *