preface

Hello everyone, I’m Asong and this is my ninth original article. Today to introduce several hot loading methods, greatly improve our development efficiency. All implementations of this article are based on GIN framework. The official account has the latest official Chinese document of 2020, and the background reply: GIN (case insensitive) can be obtained.

All project effects in this article are based on the gin_jwT_Swagger open source project, project address: github.com/asong2020/G…

Article link: I heard you still can’t JWT and swagger- I don’t even eat food with a practical project I came

What is hot loading

If you are a Python developer, you should be familiar with this. Flask or Django support real-time loading. When we make changes to the code, the application is automatically reloaded and executed, which is very convenient for us to test the code quickly without having to manually recompile it every time.

If you’re a JAVA developer, not only will you hear overloading, but hot deployment will follow. In hot deployment, a container (supporting multiple applications) starts a single application without restarting it. Hot loading typically means restarting the application (JVM) to update a class or configuration file separately.

Now that you know what hot loading is, what should you do if you want to use it in your project? Here are a few methods, want to use which to use which, is so bold. Hum!!!!!!

1. Air

Making address: https://github.com/cosmtrek/air Star: 1.8 k

It has the following features:

  • Color log output
  • Custom build or binary commands
  • Support for ignoring subdirectories
  • Supports listening for new directories after startup
  • A better build process

The installation

$ go get -u github.com/cosmtrek/air
Copy the code

use

In order for us to use the command line, we need to add alias air=’~/.air’ to your.bashrc or.zshrc, depending on your system. Since I’m a MAC, I added alias air=’~/.air’ to vim ~/.zshrc.

Then run the following command

#1. Go to your own project directory
$ cd /your_project
#2. Find if the '.air.conf 'configuration file exists in your project
$ air -c .air.conf
#3. If no, create one
$ touch .air.conf
#4. Copy the following 'air.conf.example' into your '.air.conf '

#5. Enable hot loading
$ air 
#6. Enable hot loading tape printinglog
$ air -d
Copy the code

Air. Conf. Example example

Reference: Portal

root = "."
tmp_dir = "tmp"

[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./tmp/main ."
# Binary file yields from `cmd`.
bin = "tmp/main"
# Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Watch these filename extensions.
include_ext = ["go"."tpl"."tmpl"."html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets"."tmp"."vendor"."frontend/node_modules"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.
exclude_file = []
# This log file places in your tmp_dir.
log = "air.log"
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop running old binary when build errors occur.
stop_on_error = true
# Send Interrupt signal before killing process (windows does not support this feature)
send_interrupt = false
# Delay after sending Interrupt signal
kill_delay = 500 # ms

[log]
# Show log time
time = false

[color]
# Customize each part's color. If no color found, use the raw app log. main = "magenta" watcher = "cyan" build = "yellow" runner = "green" [misc] # Delete tmp directory on exit clean_on_exit = trueCopy the code

Results demonstrate

2. Fresh

Making address: https://github.com/gravityblast/fresh Star: 2.8 K

Fresh is a command-line tool that generates or restarts Web applications every time a Go or template file is saved. Fresh monitors file events and generates and restarts the application every time a file is created/modified/deleted. If go Build returns an error, it will record it in the TMP folder.

The installation

$ go get github.com/pilu/fresh
Copy the code

use

#Go to your project directory
$ cd /your_project
#Start the
$ fresh
Copy the code

Results demonstrate

3. bee

Making address: https://github.com/beego/bee Satr: 1.1 K

Bee is a hot compilation tool for Beego framework. It can also heat compile GIN framework, which is very convenient to use and has many functions. I will not expand it here.

The installation

# To install bee use the go get command:
$ go get github.com/beego/bee
# If you already have bee installed, updating bee is simple:
$ go get -u github.com/beego/bee
# Then you can add bee binary to PATH environment variable in your ~/.bashrc or ~/.bash_profile file:
$ export PATH=$PATH:<your_main_gopath>/bin
Copy the code

use

#Go to your project directory, note: To use bee projects, you must be in the GOPATH directory
$ cd /your_project
#To run the program
$ bee run
Copy the code

Results demonstrate

4. gowatch

Making address: https://github.com/silenceper/gowatch Star

Go program hot compilation tool, by listening to the current directory under the relevant file changes, real-time compilation.

The installation

$ go get github.com/silenceper/gowatch
Copy the code

use

After the installation is complete, you can run the gowatch command. The command parameters are as follows:

  • -o: specifies the build target file path
  • -p: optional, specify build package (can also be a single file)
  • -args: optional, specify program runtime parameters, for example: -args=’-host=:8080,-name=demo’
  • -v: optional. Gowatch version information is displayed
$ gowatch -o ./bin/demo -p ./cmd/demo
Copy the code

You can modify the gowatch configuration file gowatch.yml

In most cases, executing the gowatch command without changing the configuration will suffice, but some configurations are provided for customization, such as creating gowatch.yml files in the execution directory:

# gowatch.yml configuration example

The name of the executable generated under execution. The default is the name of the current directory
appname: "test"
# specify the compiled target file directory
output: /bin/demo
# Append the suffix to the listening file name, default is only '.go' file
watch_exts:
    - .yml
The default listening directory is the current directory
watch_paths:
    - ../pk
Additional parameters that need to be added when executing the command
cmd_args:
    - arg1=val1
Additional parameters that need to be added when building the command
build_args:
    - -race
The current environment variable is loaded by default
envs:
    - a=b
Whether to listen for file changes in the 'vendor' folder
vendor_watch: false
No need to listen to the directory name
excluded_paths:
    - path
# main Package path, can also be a single file, multiple files are separated by commas
build_pkg: ""
# build tags
build_tags: ""

# Whether to disable automatic running
disable_run: false
Copy the code

Project presentations

5. gin

Making address: https://github.com/codegangsta/gin Star: 3.4 K

Gin is a simple command-line utility for reloading Go Web applications in real time. As long as GIN is running in your application directory, your network application provides GIN as a proxy. When gin detects changes, it will automatically recompile your code. Your application will restart the next time it receives an HTTP request.

Gin adheres to the principle that “silence is gold”, so it only complains if a compiler error occurs or if a compilation succeeds after an error occurs.

The installation

$ go get github.com/codegangsta/gin
# Then verify that gin was installed correctly:
$ gin -h
Copy the code

use

$ gin run main.go
Copy the code

Options:

--laddr value, -l value listening address for the proxy server --port value, -p value port for the proxy server (default: 3000) --appPort value, -a value port for the Go web server (default: 3001) --bin value, -b value name of generated binary file (default: "gin-bin") --path value, -t value Path to watch files from (default: ".") --build value, -d value Path to build files from (defaults to same value as --path) --excludeDir value, -x value Relative directories to exclude --immediate, -i run the server immediately after it's built --all reloads whenever any file changes, as opposed to reloading only on .go file change --godep, -g use godep when building --buildArgs value Additional go build arguments --certFile value TLS Certificate --keyFile value TLS Certificate Key --logPrefix value Setup custom log prefix --notifications enable desktop notifications --help,  -h show help --version, -v print the versionCopy the code

Project presentations

6. realize

Making address: https://github.com/oxequa/realize Star: 3.8 K

Realize is Golang’s real-time reload and task runner. Its main functions are as follows:

  • High performance Real-time refresh.
  • Manage multiple projects simultaneously.
  • View by custom extension and path.
  • All Go commands are supported.
  • Switch between different versions of Go.
  • Custom environment variables for the project.
  • Execute custom commands before and after file changes or globally.
  • Export logs and errors to external files.
  • Step by step project initialization.
  • Redesigned panel to display build errors, console output and warnings.

The installation

$ go get github.com/oxequa/realize
Copy the code

My GO version is 1.14, so the installation is successful in the following way:

$  GO111MODULE=off go get github.com/oxequa/realize
Copy the code

use

#Initialize the default configuration first
$ realize init
#Perform project
$ realize start
#Add a command
$ realize add
#The delete command
$ realize init
Copy the code

Options:

--name="name"               -> Run by name on existing configuration
--path="realize/server"     -> Custom Path (if not specified takes the working directory name)
--generate                  -> Enable go generate
--fmt                       -> Enable go fmt
--test                      -> Enable go test
--vet                       -> Enable go vet
--install                   -> Enable go install
--build                     -> Enable go build
--run                       -> Enable go run
--server                    -> Enable the web server
--open                      -> Open web ui in default browser
--no-config                 -> Ignore an existing config / skip the creation of a new one
Copy the code

Examples:

$ realize start
$ realize start --path="mypath"
$ realize start --name="realize" --build
$ realize start --path="realize" --run --no-config
$ realize start --install --test --fmt --no-config
$ realize start --path="/Users/username/go/src/github.com/oxequa/realize-examples/coin/"
Copy the code

Realize use method more, interested can go to the official documentation to learn.

Project presentations

conclusion

Well, that’s the end of this article. Summarized 6 kinds of hot loading methods, each has its own characteristics, according to the likes of preferences, choose a bai, greatly improve our development efficiency!!

I’m Asong, a little programmer who wants to get better. Welcome to your attention, we will see you next time!!

Recommended previous articles:

  • I heard you don’t know how to JWT or swagger. – I’m skipping meals and I’m here with my practice program
  • Master these Go language features and you will improve your level by N levels (ii)
  • Go multiplayer chat room, here you can talk about anything!!
  • GRPC Practice – Learning GRPC is that simple
  • Go Standard library RPC practices
  • Asong picked up English and translated it with his heart