Guide for Implementing Live Reload Using Golang Air

Air is a command-line utility designed for live-reloading Go applications during development. It serves as a tool that enables Go applications to reload in real-time.

Guide for Implementing Live Reload Using Golang Air

While coding, live reload lets developers see their changes in real time. This saves time by eliminating the need to manually stop and restart the server after changes. Some Go live reload frameworks can automatically reload your application after source code changes. This article will demonstrate live reload in Go using the Air library.

>> Read more about Golang:

Introduction To The Golang Air Library

Air is a command-line utility designed for live-reloading Go applications during development. It serves as a tool that enables Go applications to reload in real-time.

Aside from Air, other well-known live reload frameworks for Go include Fresh and Realize. They operate similarly by automatically rebuilding and restarting your application upon detecting changes to the source code.

  • Fresh is a command-line tool designed for use with any Go web server, easily integrated into your build process.
  • Realize is a Go-based build system that furnishes live reloading functionality for Go applications.

Given the similarity in functionality among these options, the choice of which framework to use in your Go project largely depends on personal preference. Experiment with each one to determine which feels the most straightforward or intuitive for your workflow.

What is Live Reload?

Live reload is a development feature that automatically refreshes the application or server whenever you make changes to the source code. It is particularly useful during development and debugging, as it eliminates the need to manually stop and restart the application each time you modify the code.

When To Implement Live Reload?

Live reload is beneficial in various scenarios, including:

Web Development

Live reload is commonly used in web development for both client-side (HTML, CSS, JavaScript) and server-side (backend code) changes. When you save a file, the web page is automatically refreshed to reflect the latest changes without requiring a manual refresh.

Frontend Frameworks

Frontend frameworks like React, Angular, and Vue often come with built-in or easily integrable tools that support live reload. This accelerates the development process and allows developers to see immediate changes in the user interface.

Backend Development

During backend development, live reload is useful for automatically restarting the server when changes are made to the server-side code. This is common in frameworks like Express (Node.js), Django (Python), and others.

Cross-Platform Development

Live reload is valuable in cross-platform development scenarios, such as mobile app development with frameworks like React Native or Flutter. Changes to the code can trigger automatic updates on the connected devices or emulators.

Go Language (Golang)

The Go programming language has good support for live reload during development. Tools like gin, fresh, and air are popular in the Go community. They monitor code changes and automatically rebuild and restart the Go application, providing a seamless development experience.

Example using gin:

go get -u github.com/codegangsta/gin
gin run main.go

Example using air:

go get -u github.com/cosmtrek/air
air

Live Reload vs. Hot Reload in Go

In Go, the term "live reload" pertains to the capability of automatically refreshing and updating an application without the need for manual stopping and restarting. 

A similar concept known as "hot reload" specifically involves updating the application's code while it is still running, without disrupting its current state or any ongoing processes.

Both live reload and hot reload are advantageous in development, enabling faster iteration and testing of code changes without the necessity for manual interruption and restart. Depending on the complexity of the application, implementing hot reloading may not be feasible or could present more challenges.

Go and Gin projects lack inherent support for live reload functionality. Therefore, let's explore how to configure the Air library to implement live reload in Go and Gin projects.

>> Read more: Gin-Gonic Tutorial: API Development in Go Using Gin Framework

6 Steps for Using Golang Air with Gin Gonic

Step 1: Install Gin Gonic and Air

Open your terminal and run the following commands to install Gin Gonic and Air:

# Install Gin Gonic
go get -u github.com/gin-gonic/gin

# Install Air
go get -u github.com/cosmtrek/air

Step 2: Create a Simple Gin Application

Create a new file named main.go with the following content:

// main.go
package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
	// Create a new Gin router
	router := gin.Default()

	// Define a route
	router.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "Hello, Gin!",
		})
	})

	// Run the server on port 8080
	router.Run(":8080")
}

Step 3: Create an Air Configuration File

Create a file named air.toml with the following content:

# air.toml
root = "."
tmp_dir = "tmp"
build_cmd = "go build -o ./tmp/main ."
run_cmd = "./tmp/main"

Step 4: Run the Application with Air

In your terminal, navigate to the project directory and run the application using Air:

air

This will start your Gin application with live-reloading. As you make changes to your code and save the files, Air will automatically detect the changes and restart the server.

Step 5: Test Your Application

Open your web browser and go to http://localhost:8080. You should see the JSON response:

{"message":"Hello, Gin!"}

Step 6: Make Changes and See Live-Reloading in Action

Make some changes to your main.go file, save it, and observe how Air automatically restarts the server. Check your browser to see the updated response without manually restarting the application.

6 Steps for Using Golang Air with Echo

Step 1: Install Echo and Air

Open your terminal and run the following commands to install Echo and Air:

# Install Echo
go get -u github.com/labstack/echo/v4

# Install Air
go get -u github.com/cosmtrek/air

Step 2: Create a Simple Echo Application

Create a new file named main.go with the following content:

// main.go
package main

import (
	"github.com/labstack/echo/v4"
	"net/http"
)

func main() {
	// Create a new Echo instance
	e := echo.New()

	// Define a route
	e.GET("/", func(c echo.Context) error {
		return c.JSON(http.StatusOK, map[string]string{
			"message": "Hello, Echo!",
		})
	})

	// Start the server on port 8080
	e.Start(":8080")
}

Step 3: Create an Air Configuration File

Create a file named air.toml with the following content:

# air.toml
root = "."
tmp_dir = "tmp"
build_cmd = "go build -o ./tmp/main ."
run_cmd = "./tmp/main"

Step 4: Run the Application with Air

In your terminal, navigate to the project directory and run the application using Air:

air

Step 5: Test Your Application

Open your web browser and go to http://localhost:8080. You should see the JSON response:

{"message":"Hello, Echo!"}

Step 6: Make Changes and See Live-Reloading in Action

As above.

6 Steps for Using Air with Fiber

Step 1: Install Fiber and Air

Open your terminal and run the following commands to install Fiber and Air:

# Install Fiber
go get -u github.com/gofiber/fiber/v2

# Install Air
go get -u github.com/cosmtrek/air

Step 2: Create a Simple Fiber Application

Create a new file named main.go with the following content:

// main.go
package main

import (
	"github.com/gofiber/fiber/v2"
)

func main() {
	// Create a new Fiber instance
	app := fiber.New()

	// Define a route
	app.Get("/", func(c *fiber.Ctx) error {
		return c.JSON(map[string]string{
			"message": "Hello, Fiber!",
		})
	})

	// Start the server on port 8080
	app.Listen(":8080")
}

Step 3: Create an Air Configuration File

Create a file named air.toml with the following content:

# air.toml
root = "."
tmp_dir = "tmp"
build_cmd = "go build -o ./tmp/main ."
run_cmd = "./tmp/main"

Step 4: Run the Application with Air

In your terminal, navigate to the project directory and run the application using Air:

air

This will start your Fiber application with live-reloading. As you make changes to your code and save the files, Air will automatically detect the changes and restart the server.

Step 5: Test Your Application

Open your web browser and go to http://localhost:8080. You should see the JSON response:

{"message":"Hello, Fiber!"}

Step 6: Make Changes and See Live-Reloading in Action

As above.

4 Steps For Using Golang Air with Docker Containers

One of the main benefits of using live reload with a Docker container in your Go application is that it allows you to iterate quickly on your code without stopping and starting the container each time.

This becomes particularly advantageous when crafting and validating applications within a container, facilitating the prompt and effortless identification and resolution of issues.

To integrate the live reload library with Docker, you must establish a volume mount for your local source code directory in the Docker container. This setup empowers the Air library to monitor code alterations and autonomously refresh the server as needed.

>> Read more: How To Create Containerizing Microservices With Docker?

Step 1: Create a Dockerfile with instructions to install and run Air

FROM golang:latest

# Set the current working directory inside the container
WORKDIR /app

# Copy go.mod and go.sum files to the workspace
COPY go.mod go.sum ./

# Download all dependencies
RUN go mod download

# Copy the source from the current directory to the workspace
COPY . .

# Build the Go app
RUN go build -o main .

# Expose port 8080 to the outside world
EXPOSE 8080

# Command to run the executable
CMD ["air"]

Step 2: Create an .air.toml file

Create an .air.toml file in the root of your project containing the following:

root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"

[build]
  args_bin = []
  bin = "./tmp/main"
  cmd = "go build -o ./tmp/main ."
  delay = 1000
  exclude_dir = ["assets", "tmp", "vendor", "testdata"]
  exclude_file = []
  exclude_regex = ["_test.go"]
  exclude_unchanged = false
  follow_symlink = false
  full_bin = ""
  include_dir = []
  include_ext = ["go", "tpl", "tmpl", "html"]
  kill_delay = "0s"
  log = "build-errors.log"
  send_interrupt = false
  stop_on_error = true

[color]
  app = ""
  build = "yellow"
  main = "magenta"
  runner = "green"
  watcher = "cyan"

[log]
  time = false

[misc]
  clean_on_exit = false

[screen]
  clear_on_rebuild = false

Step 3: Build the Docker image

docker build -t airy-app .

Step 4: Run the server in a Docker container

docker run -p 8080:8080 -v $PWD:/app airy-app
  • docker run: This is the command used to run a Docker container.
  • p 8080:8080: This option maps port 8080 on the host machine to port 8080 in the container. It allows external systems to access the application running inside the container via port 8080.
  • v $PWD:/app: This option mounts the current working directory ($PWD) on the host machine to the /app directory inside the container. This is a volume mount, and it allows the container to access the files and directories in the current working directory of the host. Changes made to files in either the host or the container are reflected in both.
  • airy-app: This is the name of the Docker image you are running. It specifies the image from which the container will be created.

docker run command is creating and running a container from the airy-app image. It maps port 8080 from the host to port 8080 in the container, allowing external access to the application. It also mounts the current working directory on the host to the /app directory inside the container, facilitating data sharing between the host and the container.

Pros and Cons of Using Live Reload in Go

Pros

Live reloading is a development tool that significantly enhances the efficiency of the coding process. It enables automatic and instantaneous updates to an application whenever changes are made to the source code, eliminating the need for manual restarts. Here's why it's advantageous:

  • Enhanced Development Speed: Traditional development often involves stopping the application and restarting it to see code changes take effect. Live reloading eliminates this delay by dynamically applying changes as soon as the code is saved, resulting in a faster development workflow.
  • Minimized Downtime: Without live reloading, developers frequently experience downtime waiting for the application to restart after modifications. Live reloading minimizes this downtime, allowing developers to stay focused on coding without interruptions.
  • Facilitates Debugging: Live reloading is an invaluable debugging tool. It expedites the identification and resolution of issues by automatically refreshing the application whenever changes are made. This immediate feedback loop accelerates the debugging process.
  • Efficient Testing: Continuous and automated reloading aids in testing different scenarios, ensuring that changes are thoroughly tested without the need for manual intervention.
  • Seamless Container Development: In containerized environments like Docker, live reloading is valuable for quickly adapting to changes, making it easier to identify and resolve issues within the containerized application.
  • Ideal for Complex Projects: In intricate projects with numerous dependencies or extended startup times, live reloading proves especially beneficial. It simplifies the development process by providing real-time visibility into the effects of code alterations without the need for repeated manual interventions.

In essence, live reloading is a time-saving mechanism that streamlines the development workflow, reduces downtime, aids in debugging, and proves particularly advantageous for projects with intricate structures or extended startup processes.

Cons

  • Resource Intensive: Live reloading tools often consume additional system resources to monitor and reload the application. This could lead to increased memory and CPU usage during development.
  • Potential for Unintended Side Effects: Automatic reloading might introduce unexpected behavior, especially in complex applications, as it interrupts the existing state and ongoing processes. Developers need to be cautious about potential side effects.
  • Compatibility Challenges: Integrating live reload functionality may require adjustments to your project structure or dependencies. Some projects might not be compatible with certain live reloading tools.
  • Build Time Overhead: The process of rebuilding and restarting the application during live reloading introduces a slight delay. While this delay is usually minimal, it can add up over time and impact the overall development experience.
  • Dependency on Specific Tools: Live reloading is often facilitated by specific tools or libraries (e.g., Air, Fresh). Depending on these tools introduces a dependency that may need to be managed and updated.

Live reloading can significantly improve the development experience by providing rapid feedback on code changes. However, developers should be aware of the potential drawbacks, including resource consumption, unintended side effects, and the need for careful integration in certain project environments. The decision to use live reloading should be based on the specific needs and characteristics of the project.

>> You may be interested in:

Conclusion

To sum up, the importance of live reloading in the development process cannot be overstated. It serves as a catalyst for a more efficient workflow, allowing developers to witness the impact of their code changes in real-time.

In the case of Go (Golang), tools like Air play a pivotal role by automating the rebuild and restart process, fostering a continuous development experience. This not only accelerates iteration speed but also enhances overall productivity, as developers can maintain focus on coding without the disruptions caused by manual interventions. 

In essence, live reloading, exemplified by tools like Air, is an indispensable asset in modern development environments, contributing to quicker feedback loops and a more responsive coding experience.

>>> Follow and Contact Relia Software for more information!

  • golang
  • coding
  • development
  • Mobile App Development