Best way to auto reload golang

Last Updated Dec 09, 2022

If you're transitioning from other language to Go (such as nodejs), you're likely missing a key feature you had in JavaScript, Svelte, Angular, React, Vue, etc.

All of them are quick to develop since they retain your modifications when you save the files you're working on; the same is true when you use express; say nodemon :)

There are several ways to accomplish this in Go or maybe another language. One of them, the greatest one in my opinion, is entr it is simple, tiny and fast.

If you also think it's a waste of time, pressing cmd+c in terminal to stop the golang process and then and enter every single time then read on.

entr: A utility for running arbitrary commands when files change

entr is a command line tool that lets you run any command whenever any of the files you tell it to watch change. For instance:

find . -name *.go | entr -r go run main.go

The find command lists all the files with extension .go in the current dir and then entr will run (and reload) if any of the files you listed change.

With a simple command above, we obtain all of these advantages:

  1. immediately start the server
  2. block until any of the listed files change
  3. terminate the background process
  4. wait for the server to exit before restarting (!)

Now, if we make any changes to the golang file, it will detect it, compile it and run it. Neat huh? But what about the html template? easy:

find . -name *.go -o -name '*.html' | entr make

One of entr's many helpful options is the -c flag, which wipes the screen clean before a run begins. A sample that monitors whether or not new folders or files have been added can be found on the entr page

Overall, entr is a small, useful utility that makes programming much easier.

Others articles of me write about golang

If you like golang, here is some others articles of the same author (me) about golang topic. Check it out !

  1. golang error handling
  2. golang context best practices
  3. Golang composition over Inheritance all you need to know

Hi there. Nodeepshit is a hobby website built to provide free information. There are no chargers to use the website.

If you enjoy our tutorials and examples, please consider supporting us with a cup of beer, we'll use the funds to create additional excellent tutorials.

If you don't want or unable to make a small donation please don't worry - carry on reading and enjoying the website as we explore more tutorials. Have a wonderful day!