Debugging Golang

To do anything complex in Golang, it’ll be necessary to be able to debug your code at runtime.

Setting up Go’s debugger

For starters, we’re using Visual Studio Code as our IDE.

Install delve

Delve is needed to debug Go.

For us on Fedora, installation is a matter of running:

> go get github.com/derekparker/delve/cmd/dlv

Instructions for other operating systems are available on Delve’s Github page.

Debug Golang in Visual Studio Code

Open a new Visual Studio Code window open to a workspace you’d like to debug. For this walkthrough, it’ll be simple-webapp, from making a simple webapp in Golang:

Configuring the debugger

Open the Debug window (in Fedora, Control + Shift + D). You should see a panel like this: Screenshot of VS Code debug panel

Click the green arrow next to the debug screen, and choose Go in the dropdown. Doing so will create a new file named launch.json with the following content:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "remotePath": "",
            "port": 2345,
            "host": "127.0.0.1",
            "program": "${workspaceRoot}",
            "env": {},
            "args": [],
            "showLog": true
        }
    ]
}

Running the debugger

Click the green debug icon and hit “Launch”. The Debug Console appears with the following content: Screenshot of VS Code debug panel

At this point, you can set breakpoints by clicking in the margin to the left of the code lines.

I was able to debug code lines inside the main() method of webapp.go. The debugger appears to have difficulty hitting breakpoints inside the viewHandler() method.

When it’s all working, you should be able to step in / step out of code like so: Stepping in debugged code.

Stopping the debugger

Normally you can stop the debugger with the red “stop” icon on the debug popup menu.

Sometimes the debug popup disappears and I can’t get it back. When this happens, it leaves the program I’m debugging running in the background. To kill this process, do the old ps / kill routine:

> ps -ef | grep go
# Look for a line running the program, such as:
acuga    22324     1  0 14:45 tty2     00:00:00 /home/acuga/Code/go-work/src/bitbucket.org/theandruu/go-public/simple-webapp/debug

# And use it's PID (22324 in the above example) to kill the process:
> kill -9 22324
◀   Building a simple webapp Setting up a Go webapp on App Engine   ▶