1. Introduction
Debugging is an essential part of software development. It helps developers understand how an application behaves during execution, identify unexpected behaviour, trace errors, and fix bugs.
Go provides several debugging capabilities through Delve (dlv), a debugger specifically designed for Go applications. Visual Studio Code integrates with Delve through the official Go extension, providing a graphical interface for debugging Go programs.
This document serves as a practical reference for debugging Go applications using VS Code and Delve.
What we will cover
- Understanding Delve and its role in Go debugging.
- Setting up the Go debugging environment in VS Code.
- Creating and configuring
launch.json. - Setting and managing breakpoints.
- Inspecting variables and expressions.
- Stepping through application execution.
- Using the Delve command-line interface.
- Debugging tests and existing processes.
- Common debugging issues and troubleshooting.
2. Understanding Delve
Delve (dlv) is a debugger designed specifically for the Go programming language.
It allows developers to pause program execution, inspect variables, examine function calls, investigate go-routines, and step through code to understand what is happening internally.
Unlike relying entirely on print statements (fmt.Println) or application logs, a debugger allows you to inspect the application's state at a particular point during execution.
What can Delve do?
| Feature | Description |
|---|---|
| Breakpoints | Pause execution at specific lines or functions. |
| Variable inspection | Examine the values of variables during execution. |
| Step execution | Execute code one statement at a time. |
| Call stack inspection | Understand the sequence of function calls. |
| Go-routine inspection | Examine concurrent execution in Go applications. |
| Expression evaluation | Evaluate expressions while the program is paused. |
| Conditional breakpoints | Pause execution only when a specified condition is met. |
Why Delve?
Go applications use go-routines extensively for concurrency. Delve understands Go's runtime and provides debugging capabilities suited to Go's execution model.
VS Code uses Delve behind the scenes to provide its debugging functionality.
3. Setting Up the Debugging Environment
Before debugging Go applications in VS Code, ensure the following are installed:
- Go programming language.
- Visual Studio Code.
- The official Go extension for VS Code.
- Delve debugger.
Step 1: Install the Go extension
Open VS Code:
- Navigate to Extensions.
- Search for
Go. - Install the official extension published by the Go team.
The extension provides Go language support, formatting, testing, code navigation, and debugging integration.
Step 2: Install or update Delve
You can install Delve manually using:
go install github.com/go-delve/delve/cmd/dlv@latest
Ensure your Go binary directory is included in your system's PATH.
Check whether Delve is installed:
dlv version
You can also install or update Delve directly from VS Code:
- Open the Command Palette (
Ctrl + Shift + P). - Search for
Go: Install/Update Tools. - Select
dlv. - Install or update it.
Note: The Go extension can also prompt you to install or update Delve when you first start a debugging session.
4. Starting Your First Debugging Session
VS Code provides a built-in debugging interface that allows you to debug Go applications without manually interacting with the Delve terminal.
Step 1: Open your Go project
Open the project directory in VS Code.
For example:
my-go-project/
├── go.mod
├── main.go
├── handlers/
│ └── handler.go
└── services/
└── user.go
Step 2: Open the Run and Debug panel
You can access the debugging interface by:
- Selecting Run and Debug from the Activity Bar.
- Using the keyboard shortcut
F5. - Opening the Command Palette and searching for debugging commands.
Step 3: Create a debugging configuration
If your project does not have a debugging configuration, VS Code can generate one automatically.
Select:
Run and Debug → create a launch.json file → Go
This creates a .vscode directory containing a launch.json file.
Step 4: Start debugging
Open the Go file or package you want to debug.
Press F5 to start the debugging session.
VS Code will use Delve to build and launch the application.
5. Understanding launch.json
The launch.json file defines how VS Code should start or attach to a Go application during debugging.
It is normally located at:
.vscode/launch.json
A basic configuration looks like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Go Application",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}"
}
]
}
Understanding the configuration
| Property | Purpose |
|---|---|
name |
Name displayed in the debugging configuration dropdown. |
type |
Specifies the debugger extension. For Go, use go. |
request |
Determines whether to launch or attach to a process. |
mode |
Determines how the application should be debugged. |
program |
Specifies the Go file or package directory to debug. |
args |
Supplies command-line arguments to the application. |
env |
Defines environment variables for the application. |
cwd |
Sets the application's working directory. |
buildFlags |
Passes additional flags to the Go compiler. |
Common debugging modes
| Mode | Purpose |
|---|---|
debug |
Builds and debugs a Go application. |
test |
Runs and debugs Go tests. |
exec |
Debugs an already compiled binary. |
auto |
Automatically chooses between debugging an application and a test. |
Example: Debugging with environment variables
Some applications require environment variables to run correctly.
For example:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Application",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"env": {
"APP_ENV": "development",
"PORT": "8080"
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}
This configuration starts the application with the specified environment variables.
Important: Avoid committing real credentials, passwords, API keys, or other secrets to launch.json. Use environment files or your organization's approved secrets management approach.
6. Working with Breakpoints
A breakpoint tells the debugger where to pause program execution.
Instead of allowing an application to execute all its instructions, you can pause it at a specific point and inspect what is happening.
Setting a breakpoint
In VS Code:
- Open the Go source file.
- Locate the line you want to investigate.
- Click in the editor's left margin beside the line number.
A red dot indicates that a breakpoint has been created.
You can also use F9 to toggle a breakpoint on the current line.
Types of breakpoints
1. Standard breakpoints
Pause execution whenever the application reaches a particular line.
Useful when investigating unexpected behaviour in a function.
2. Conditional breakpoints
Pause execution only when a specified condition evaluates to true.
For example:
if userID == 100
This is useful when a function is called repeatedly but you only want to investigate a particular case.
3. Function breakpoints
Pause execution whenever a particular function is called.
Useful when you know which function is responsible for unexpected behaviour but do not know exactly where to place a breakpoint.
4. Logpoints
Log information to the Debug Console without pausing program execution.
Useful when you want to inspect values without interrupting the application's execution.
7. Stepping Through Code
Once execution reaches a breakpoint, you can control how the application continues.
VS Code provides several execution controls.
| Action | Shortcut | Description |
|---|---|---|
| Continue | F5 | Resume execution until the next breakpoint. |
| Step Over | F10 | Execute the current line and move to the next line without entering called functions. |
| Step Into | F11 | Enter the function being called. |
| Step Out | Shift + F11 | Finish executing the current function and return to its caller. |
| Restart | Ctrl + Shift + F5 | Restart the debugging session. |
| Stop | Shift + F5 | Stop the debugging session. |
Understanding the difference
Consider the following example:
func main() {
result := calculateTotal(10, 20)
fmt.Println(result)
}
func calculateTotal(a, b int) int {
return a + b
}
Suppose execution is paused at:
result := calculateTotal(10, 20)
-
Step Over: Executes
calculateTotal()and moves to the next statement inmain(). -
Step Into: Enters
calculateTotal()so you can inspect its execution. - Step Out: Finishes the current function and returns to the calling function.
These controls are particularly useful when tracing execution across multiple functions.
8. Inspecting Variables and Expressions
One of the most useful debugging capabilities is being able to inspect variables while an application is paused.
VS Code provides several ways to do this.
8.1 Hover over variables
While debugging, hover your mouse over a variable in the source code.
VS Code displays its current value.
This is useful when you want to quickly inspect a variable without opening another panel.
8.2 Variables panel
The Variables section in the Run and Debug panel displays:
- Local variables.
- Function arguments.
- Other available variables depending on the selected stack frame and debugger configuration.
You can expand objects and structures to inspect their individual fields.
8.3 Debug Console
The Debug Console allows you to evaluate expressions while the application is paused.
For example:
user.ID
len(users)
request.URL.Path
You can also inspect more complicated expressions supported by Delve.
8.4 Watch expressions
The Watch section allows you to monitor specific variables or expressions.
For example:
user.ID
len(items)
The debugger automatically evaluates these expressions as execution pauses and the selected stack frame changes.
This is useful when investigating variables whose values change throughout execution.
8.5 Inline values
VS Code can display variable values directly in the editor while debugging.
You can enable this through your VS Code settings:
{
"debug.inlineValues": true
}
9. Using Delve from the Terminal
Although VS Code provides a graphical debugging interface, Delve can also be used directly from the terminal.
This is particularly useful when debugging applications in environments where VS Code is unavailable.
Start a debugging session
Navigate to the Go package directory and run:
dlv debug
This compiles the current package and starts a debugging session.
You should see the Delve prompt:
(dlv)
The program is loaded but has not necessarily started executing.
Common Delve commands
| Command | Description |
|---|---|
help |
Displays available debugger commands. |
continue |
Resumes program execution. |
break main.main |
Sets a breakpoint at a function. |
break main.go:25 |
Sets a breakpoint at a specific line. |
breakpoints |
Lists existing breakpoints. |
clear 1 |
Removes breakpoint number 1. |
next |
Executes the next statement without entering functions. |
step |
Steps into a function. |
stepout |
Steps out of the current function. |
print variable |
Displays a variable's value. |
locals |
Displays local variables. |
args |
Displays function arguments. |
stack |
Displays the current call stack. |
goroutines |
Lists available goroutines. |
goroutine 1 |
Switches to goroutine 1. |
quit |
Exits the debugging session. |
Example debugging session
dlv debug
Inside the Delve console:
(dlv) break main.main
(dlv) continue
(dlv) next
(dlv) print variable
(dlv) stack
This workflow allows you to start an application, pause execution, inspect variables, and investigate the call stack.
10. Debugging Go Tests
Delve can also be used to debug Go tests.
This is particularly useful when a test fails unexpectedly and you need to understand why.
Using VS Code
Create a test debugging configuration:
{
"name": "Debug Go Tests",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}"
}
You can also open a test file and start debugging using F5.
Using the terminal
To debug tests in the current package:
dlv test
To run a specific test:
dlv test -- -test.run TestMyFunction
This allows you to investigate test execution using breakpoints and variable inspection.
11. Debugging an Existing Go Process
Sometimes an application is already running, and you want to investigate it without starting another instance.
VS Code supports attaching to an existing process.
A basic local attach configuration looks like this:
{
"name": "Attach to Go Process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": 0
}
When the debugging session starts, VS Code allows you to select a running process.
Alternatively, you can specify a known process ID (PID).
Important: Attaching to an existing process has platform and permission requirements. The target binary must also contain suitable debugging information.
12. Common Debugging Issues
| Problem | Possible solution |
|---|---|
| Delve is not installed | Install or update it using Go: Install/Update Tools. |
VS Code cannot find dlv
|
Check that the Go binary directory is included in PATH. |
| Breakpoint is not being hit | Confirm that the correct source file and package are being executed. |
| Variables cannot be inspected properly | Check compiler optimizations and the selected stack frame. |
| Application exits immediately | Check the application entry point, configuration and startup errors. |
| Environment variables are missing | Check the env and envFile settings in launch.json. |
| Debugging a compiled binary behaves unexpectedly | Rebuild with optimizations and inlining disabled. |
Disabling compiler optimizations
Compiler optimizations and function inlining can sometimes make debugging more difficult.
When debugging an existing binary, build it using:
go build -gcflags=all="-N -l" -o app .
Where:
-
-Ndisables optimizations. -
-ldisables inlining.
This can make variable inspection and stepping through code more predictable.
Note that these flags are primarily useful for debugging builds, not normal production builds.
13. Recommended Debugging Workflow
When investigating a bug in a Go application, the following workflow provides a useful starting point.
- Reproduce the problem: Understand what action or input triggers the unexpected behaviour.
- Identify the relevant code: Locate the function, handler, or package responsible.
- Set breakpoints: Place breakpoints at relevant execution points.
- Start debugging: Launch the application using VS Code and Delve.
- Inspect variables: Check arguments, local variables, structures and expressions.
- Step through execution: Use Step Over, Step Into and Step Out to understand the execution flow.
- Identify the root cause: Determine where the actual behaviour differs from what is expected.
- Implement a fix: Correct the underlying issue.
- Verify the fix: Run the application and relevant tests again.
- Remove unnecessary breakpoints: Keep the debugging configuration clean.
14. Important Things to Remember
- Delve is the primary debugger used by the official Go extension in VS Code.
- Breakpoints allow you to pause execution at specific locations.
- The Debug Console is useful for inspecting variables and evaluating expressions.
- Step Into helps investigate function calls, while Step Over executes them without entering.
- The Call Stack helps trace how execution reached the current location.
- The Goroutines view is particularly useful when investigating concurrent Go applications.
-
launch.jsonallows you to maintain reusable debugging configurations. - Debugging and testing go hand in hand. Always verify fixes with relevant tests.
- Debugging configurations should not expose application secrets.
- Debugging builds should be kept separate from production builds.
A useful principle: You do not need to memorize every debugger command or configuration option. Understand what the debugger can do, know where to find the relevant settings, and refer to the documentation when necessary.
15. Further Reading and References
The following resources were used when preparing this reference guide:
Documentation note: Debugger features and configuration options can change between versions. Consult the official Go extension and Delve documentation when troubleshooting version-specific behaviour.
Top comments (0)