log/setup go debugger using delve and air

In debugging Go we can use [delve](go-delve/delve: Delve is a debugger for the Go programming language. (github.com)), go 3rd party debugger. Click the link to install it.

When develop go program, I like to use air to enable hot reloading, therefor we need add some configuration in air to be able use delve effectively.

Here are the configuration of .air.toml (I only show what i changed, the rest is same as default, and I configure the air for templ also)

 1[build]
 2
 3	# add the templ generate when working with templ
 4	cmd = "templ generate internal/views/ && CGO_ENABLED=0 go build -gcflags=all=\"-N -l\" -o ./tmp/main ./cmd"
 5
 6	# exclude file generated by templ, otherwise infinite loop will occur
 7	exclude_regex = ["_test.go", ".*_templ.go"]
 8
 9	# instead run the binary, we run the dlv
10	# we can add flag to our application after the '--'
11	full_bin = "dlv exec ./tmp/main --listen=127.0.0.1:2345 --headless=true --api-version=2 --accept-multiclient --continue --log -- "
12
13	# include the .templ file
14	include_ext = ["go", "tpl", "tmpl", "html", "templ"]
15

After all configuration, we can run air, it will start the program and delve, and the we can access our debugger on our editor

VSCODE
For vscode we can setup launch.json (if the file not available, vscode will ask to add the file),

 1{
 2  "version": "0.2.0",
 3  "configurations": [
 4    {
 5      "name": "Attach to Air",
 6      "type": "go",
 7      "request": "attach",
 8      "mode": "remote",
 9      "port": 2345,
10      "host": "127.0.0.1"
11    }
12  ]
13}

after that we can run the debugger on vscode using the launch.json

NEOVIM
I'm using LazyVim and installed extra plugin nvim-dap and Go.(it will automatically install nvim-dap-go). The debugger can be accessed using key <leader>da -> Debug -> type the port (in this case 2345)

Happy coding!!!