DEV Community

Cover image for Air: Live reload on Golang applications
Breno Alves
Breno Alves

Posted on

Air: Live reload on Golang applications

Go is a programming language with advanced features and clean syntax. It has a robust and well-documented common library, and has focus on good software engineering and principles.

Although Go is a great language, there's one downside: it needs to be recompiled every time after a single line change.

So, to make our lives easier in this post we're gonna learn how to use Air as our live reload.


App

Init with Go mod

go mod init helloworld

Creating App Go file

package main

import (
    "fmt"
    "net/http"
)

func main() {
    port := 3000
    fmt.Println("Starting Server on port", port)

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World"))
    })
    http.ListenAndServe(":3000", nil)
}
Enter fullscreen mode Exit fullscreen mode

Air:

Installing Air.

go get -u github.com/cosmtrek/air

Air configuration file

air init

Starting Air.

air

You'll have the following result:

Air running

Now after any file change Air will reload your app automatically.

Air reloading


Air and Docker

First we need to create a Dockerfile

# Dockerfile

FROM cosmtrek/air

RUN mkdir -p /app/dist
COPY ./ /app/
WORKDIR /app/

RUN go get -d -v ./...
RUN go install -v ./...

CMD ["air"]
Enter fullscreen mode Exit fullscreen mode

Now we need to create a docker-compose to make our life easier

# docker-compose.yml

version: '3.7'
services:
  app:
    build: .
    ports:
      - '3000:3000'
    volumes:
      - ./:/app/
Enter fullscreen mode Exit fullscreen mode

Now you just need to run docker-compose up

And you'll have the following result:

Air in docker container

References:

Top comments (4)

Collapse
 
parmcoder profile image
Possawat Sanorkam

Thank you for your post. Could you please give me the dockerfile recipe without using the image from cosmtrek/air?

Great!

Collapse
 
brenoalves profile image
Breno Alves
# binary will be $(go env GOPATH)/bin/air
curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# or install it into ./bin/
curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s

air -v
Enter fullscreen mode Exit fullscreen mode

you can find this script on air github README. Just use it to install within your docker container and I believe you're good to go :)

Collapse
 
newtonneto profile image
Newton Neto

Me ajudou demais, estou aprendendo Go e recompilar o código a cada alteração se prova algo muito irritante.

Collapse
 
lucassantos_dev profile image
Lucas Santos

Brabo demais!!!