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)

[build]

	# add the templ generate when working with templ
	cmd = "templ generate internal/views/ && CGO_ENABLED=0 go build -gcflags=all=\"-N -l\" -o ./tmp/main ./cmd"

	# exclude file generated by templ, otherwise infinite loop will occur
	exclude_regex = ["_test.go", ".*_templ.go"]

	# instead run the binary, we run the dlv
	# we can add flag to our application after the '--'
	full_bin = "dlv exec ./tmp/main --listen=127.0.0.1:2345 --headless=true --api-version=2 --accept-multiclient --continue --log -- "

	# include the .templ file
	include_ext = ["go", "tpl", "tmpl", "html", "templ"]

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),

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to Air",
      "type": "go",
      "request": "attach",
      "mode": "remote",
      "port": 2345,
      "host": "127.0.0.1"
    }
  ]
}

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!!!

Written on 2024-02-22 04:43:00 +0700 Edited on 2024-03-10 13:21:00 +0700