Technology at Flyclops

Using gofmt and goimports in IntelliJ IDEA

posted in Code on 2016-06-14 12:34:10 EDT by Dave Martorana

Update 2016-11-30: uploaded a new screenshot of the file watcher screen in 2016.3

IntelliJ IDEA is arguably the best Go IDE on the planet. The go-lang-idea-plugin turns IDEA into a full-featured IDE, and does so incredibly well. In fact, since moving to it, I’m not sure how I used anything else.

In any case, the one thing really missing from the IDE is auto-formatting with gofmt or formatting+imports with goimports - but it’s pretty easy to get working.

Setup

First, install IDEA and the go-lang-idea-plugin… plugin. Next, install the “File Watchers” plugin from Intellij:

"File Watchers" plugin

Automatically calling goimports

Unfortunately, you’ll need to set up a file watcher for each project, but it’s not too tedious. With your project open, go to the Preferences screen, and open the “Tools” tree. Select “File Watchers” and click the + button to create a new file watcher.

Fill in the information similarly to below (make sure “Program” points to your goimports binary):

goimports set up

A few tips:

  • Putting -w in the “Arguments” field will tell goimports to overwrite the file, not dump its output to stdout.
  • Make sure to un-check “Immediate file synchronization” or the IDE will spaz out on you
  • I like to check “Trigger watcher regardless of syntax errors,” but YMMV

That’s it. Click save on any document in your project, and (assuming there are no errors that break goimports) your document will be formatted and imports will be automatically filled in.

This last little step is all that Sublime Text or Atom (or Vim-Go) had on IntelliJ IDEA. After this, in my humble opinion, IntelliJ IDEA stands alone as the best Go IDE out there.

Note: To use gofmt instead of goimports, simply replace the “Program” field with the path to gofmt instead of goimports and you’ll get the results you’re looking for.