getting started with vscode golang debugging

Author

Reads 1.1K

From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio
Credit: pexels.com, From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio

Getting started with VSCode GoLang debugging is easier than you think. First, you'll need to install the Go extension, which can be done by opening the Extensions panel in VSCode and searching for "Go".

To set up your workspace, create a new Go module by running the command "go mod init" in your terminal, followed by "go get" to install any dependencies. This will create a go.mod file that VSCode can use to understand your project's dependencies.

The Go extension will also create a launch.json file in your project's .vscode directory, which is where you'll configure your debug settings. For example, you can use the "delve" debugger, which is a popular choice among Go developers.

Broaden your view: Golang Ci Linter Install

Getting Started

To start debugging your Go program in VS Code, you'll want to open the file you want to debug in the editor and select the Run and Debug button from the Run view. Alternatively, you can start debugging using the Start Debugging command from the Run menu or the Command Palette.

Credit: youtube.com, Getting Started with Debugging in VS Code (Official Beginner Guide)

If you already have launch configurations for your project, the Run view will display the configuration list to choose from. If not, the extension will choose a default configuration based on the file open in the editor.

To create a custom launch configuration, click "create a launch.json file" in the Run view, choose Go: Launch Package from the debug configuration drop-down menu, and VS Code will create a launch.json file in a .vscode folder in your workspace or in your user settings.

Explore further: Golang Run Debug Mode

Get Started

To get started with debugging your Golang code in VSCode, open a file to debug in the editor, either the package main source file or a test file.

Select the Run and Debug button from the Run view. Alternatively, you can start debugging using the Start Debugging (F5) command from the Run menu or from the Command Palette (Linux/Windows: Ctrl+Shift+P, Mac: ⇧+⌘+P).

If you already have launch configurations for the project (.vscode/launch.json), the Run view will display the configuration list to choose from.

Worth a look: Vscode Golang

A Woman Wearing Headscarf in a Standing Sprint Start Position
Credit: pexels.com, A Woman Wearing Headscarf in a Standing Sprint Start Position

The Go extension will choose a default configuration based on the file open in the editor if no configuration is configured yet (no .vscode/launch.json file).

❗ If you start debugging for the first time or if the dlv executable on your system is too old to support DAP, the Go extension may ask to install or update Delve.

Semantic Syntax Highlighting

Semantic syntax highlighting can make a big difference in code readability.

To get better syntax highlighting than the default TextMate-based syntax highlighting, you can enable semantic highlighting by turning on Gopls' ui.semanticTokens setting.

Hover Information

Hovering on any variable, function, or struct will give you information on that item such as documentation, signature, etc. This is a super helpful feature that will save you time and frustration.

You can use this hover information to get a quick rundown of what a particular variable or function does, without having to leave your current workflow.

Code Navigation

Two Women Looking at the Code at Laptop
Credit: pexels.com, Two Women Looking at the Code at Laptop

Code navigation is a powerful feature in this editor. It allows you to quickly jump to specific parts of your code.

You can access code navigation features from the context menu in the editor. Press F12 to go to the source code of a type definition. The same shortcut also works for Go to Type Definition.

The Peek Definition feature is also accessible from the context menu. Press ⌥F12 (Windows Alt+F12, Linux Ctrl+Shift+F10) to bring up a Peek window with the type definition.

If you want to see all references for a type, press ⇧F12 (Windows, Linux Shift+F12). This will show you a list of all places where the type is used.

You can also use the Go to Symbol commands from the Command Palette to navigate via symbol search. Press ⇧⌘P (Windows, Linux Ctrl+Shift+P) to open the Command Palette, then select Go to Symbol in File or Go to Symbol in Workspace.

Here are the Go to Symbol commands:

You can also navigate between a Go file and its test implementation using the Go: Toggle Test File command.

Expand your knowledge: Golang Test Command

Credit: youtube.com, Hard and Symbolic Links in Linux | Linux Files and Directories

Symlink directories can be tricky to work with, especially when debugging. This is because the debugger and go compiler use the actual filenames, not the symlinked ones.

To set breakpoints in files within a symlinked directory, you need to tell the debug adapter how to properly translate the paths. This can be done by using the substitutePath property in your configuration.

For example, if your project lives in /path/to/actual/helloWorld, but it's open in vscode under the linked folder /link/to/helloWorld, you can add the following to your config to set breakpoints in the files in /link/to/helloWorld.

Debugging Basics

To launch and debug your Go project in VS Code, start by selecting Run > Start Debugging (F5) in the top menu. This will trigger the launch feature, which uses a launch request type configuration in your launch.json file.

The program attribute in your launch.json file needs to be the absolute path to either the Go file or the folder containing the main package or test file. This tells VS Code where to build and launch the program.

Credit: youtube.com, Debugging Golang CLI files with Visual Studio Code

Here's a quick rundown of the launch configurations you can use:

To set a breakpoint and start debugging, simply open a Golang source file in your project, such as main.go, and click in the gutter to the left of the line number where you want to pause the program's execution.

Launch

To launch and debug your project, select Run > Start Debugging (F5). This will start the debug session by building and launching the program.

The launch feature uses a launch request type configuration in your launch.json file. Its program attribute needs to be the absolute path to either the Go file, or folder containing the main package or test file.

You can also use remote debugging, which requires adding the port attribute to the launch configuration. VS Code will connect to the external user-specified dlv dap server at host:port and launch the target there.

For remote debugging, the program attribute must point to the absolute path to the package or binary to debug in the remote host's file system, even when substitutePath is specified.

Here are some key things to keep in mind when using remote debugging:

The launched program will be terminated when the debug session ends.

Actions

Credit: youtube.com, Debugging Techniques in Action (Cargo Defense Devlog #63)

As you start a debug session, you'll notice the Debug toolbar appearing at the top of your editor. This toolbar gives you access to various actions that help you navigate and control the debugging process.

The most basic action is to Continue or Pause the debug session, which can be done by pressing F5.

You can also Step Over or Step Into the code, which is equivalent to "next in Delve" and "step in Delve" respectively. These actions can be performed by pressing F10 and F11 respectively.

Another important action is to Step Out of the current function, which can be done by pressing Shift+F11 or ⇧F11.

If you need to restart the debug session, you can do so by pressing Ctrl+Shift+F5 or ⇧⌘F5. This is equivalent to stopping and starting the debug session.

To stop the debug session, you can press Shift+F5 or ⇧F5. This will terminate the debugee.

If you're in an Attach request, you can Disconnect from the debugee by pressing Shift+F5 or ⇧F5. This will detach you from the debugee.

In an Attach request, you can also Terminate the debugee by pressing Alt+Shift+F5 or ⌥⇧F5.

For more insights, see: Golang Delve

Data Inspection

Credit: youtube.com, What Is Effective Variable Inspection In Debugging? - Learn To Troubleshoot

Data Inspection is a crucial part of debugging, and you can do it in several ways. You can inspect variables in the VARIABLES section of the Run view or by hovering over their source in the editor.

To inspect variables, you'll need to select a stack frame in the CALL section. Variable values and expression evaluation are relative to this selected stack frame. This means you'll see the values of variables and expressions as they are at the point in the code where you've stopped execution.

By default, the VARIABLES section hides global variables, but you can still inspect them from the DEBUG CONSOLE panel. If you want to show global variables in the VARIABLES section, you can set the showGlobalVariables attribute in the launch.json configuration.

The VARIABLES section has a context menu that allows you to perform various actions on selected variables. You can set the value of a variable, copy its value, or add it to the WATCH section.

Explore further: Global Variables Golang

Credit: youtube.com, How Do You Inspect Variables In Complex Debugging? - Learn To Troubleshoot

Here are some of the actions you can perform on selected variables:

  • Set Value: allows you to set or modify simple string, numeric, or pointer values.
  • Copy Value: copies the value of the variable to the clipboard.
  • Copy as Expression: copies the value of the variable as an expression, useful for querying from the DEBUG CONSOLE panel.
  • Add to Watch: adds the variable to the WATCH section, so its value can be automatically evaluated as you debug.

The Delve debugger has some limitations when it comes to loading variables. It imposes variable loading limits to prevent loading too many variables at once and negatively impacting debugging latency. However, the dlv-dap mode takes a different approach, using interactive UI features to provide on-demand loading of individual variables.

Call Stack

The call stack is a crucial tool for debugging, allowing you to inspect all goroutines and their stacks. It's like having a map to help you navigate the code's execution.

You can select a goroutine by clicking on its call stack in the CALL STACK section. This will update the VARIABLE and WATCH sections accordingly.

The call stack is annotated with internal goroutine IDs for easy identification. The current goroutine is marked with an asterisk (*).

Here are some key features of the call stack:

  • Goroutine stacks are annotated with their internal goroutine IDs.
  • The current goroutine is marked with *. If multiple goroutines stop concurrently, Delve will pick one randomly.
  • You can select a frame of the selected goroutine.
  • Runtime stack frames are deemphasized (greyed out or collapsed).
  • Thread IDs are shown for scheduled goroutines.
  • Stop reason. It’s possible that there are multiple reasons goroutines were stopped, but currently only one reason is presented.
  • File name and line number of the frame.
  • Function name of the frame.

If you click on a goroutine call stack, the goroutine is selected, and the VARIABLE and WATCH sections are updated accordingly. The editor will also highlight the source location with more details when the program stops due to an exception, panic, or bad access error.

IntelliSense

Credit: youtube.com, VS Code tips — View regular hovers while debugging

IntelliSense is a powerful tool that helps you write code more efficiently. It's provided by the Go language server, gopls, maintained by the Go team.

The gopls settings allow you to configure the behavior of IntelliSense, giving you more control over how it works. This can be especially useful if you have specific needs or preferences.

You can access IntelliSense features through the Go language server, gopls. This means you can rely on it to provide the support you need as you write code.

A fresh viewpoint: Golang Write

Handling Stdin

The Go extension and dlv have limited access to tty, which means they can't handle STDIN.

To access terminals or read from STDIN, use the "console" launch option.

The Go extension delegates interaction with terminals to VS Code, using the Debug Adapter Protocol's RunInTerminal functionality.

For configuring VS Code's terminal related behavior, see VS Code's documentation.

You can choose between two options for the terminal: integratedTerminal or externalTerminal.

Debugging Tools

Credit: youtube.com, Ultimate guide to debugging go lang with vscode debugger

Debugging Tools can be a lifesaver when working with Go code in VSCode. The Integrated Terminal is a powerful tool that allows you to run your code and see the output directly in the editor.

You can use the built-in Go debugger to step through your code line by line, setting breakpoints and inspecting variables as needed. This is particularly useful when trying to track down tricky bugs.

The debugger also supports conditional breakpoints, which can be set to trigger only under specific circumstances, further streamlining the debugging process.

A fresh viewpoint: Golang Debugger

Dlv Command

The dlv command is a powerful tool that allows you to dynamically inspect and change debug configuration, as well as inspect the list of source code compiled in the debugged binary.

You can access the dlv command from the DEBUG CONSOLE panel in Visual Studio Code. From there, you can use the command `dlv help` to see a list of supported commands and dynamically adjustable settings.

Credit: youtube.com, dlv debug

The dlv command is particularly useful for inspecting the list of source code compiled in the debugged binary. You can use the command `dlv config -list` to see this list.

Here are some of the available commands in the dlv command:

Manually Install Dlv

If you need to install dlv manually, you can do so by finding where the Go extension finds tools. The Go extension searches for the dlv executable in directories like ${GOPATH}/bin, ${GOBIN}, and ${PATH}.

The easiest way to check the tool installation location the Go extension uses is by running the Go: Locate Configured Go Tools command from the command palette. This will give you an idea of where to install dlv.

If your Go version is 1.16 or newer, you can install dlv in the directory where the Go extension searches for tools. If your Go version is older than 1.16, you may need to specify a specific commit hash, branch name, or released version instead of the latest version.

Readers also liked: Golang Version Manager

Credit: youtube.com, How to Install Delve on Mac (OS X) for Go (Golang) debugging

You can choose to install a different version of dlv by specifying a specific commit hash, a branch name (e.g. master), or a released version. For more details about manual installation, see Delve's documentation.

If you want to explicitly specify the location of the delve binary, use the go.alternateTools setting.

Advanced Debugging

Debugging Go code in VSCode can be a challenge, but it's made easier with the right tools and techniques.

The VSCode debugger allows you to set breakpoints at specific lines of code, which can be extremely helpful when trying to identify where a program is going wrong.

One key feature of the debugger is conditional breakpoints, which allow you to set a breakpoint only when a certain condition is met. For example, you could set a breakpoint to trigger only when a specific variable is true.

In the example of debugging the "hello world" program, we saw how to use the debugger to step through the code and inspect variables. This can be a huge time-saver when trying to track down issues in your code.

The VSCode debugger also allows you to use the "go run" command to run your code in debug mode, which can be a convenient way to quickly test and debug your code.

Go Extension Architecture

Credit: youtube.com, vsCode with Golang Extension Delete Debug Binary

The Go extension in VS Code uses the Debug Adapter Protocol (DAP) to communicate with the debugger backend. This is a language-agnostic approach that allows for a generic debugger UI.

The Go extension previously used an intermediary TypeScript program to launch Delve and adapt it to DAP, but this is no longer necessary with Delve's native DAP implementation.

This new integration enables efficient and tight interaction with Delve.

Debugging Options

To debug your Go project in VS Code, you have several options. You can create a launch configuration file, which is a JSON file that defines the debugging settings for your project. This file is typically named launch.json and is stored in a .vscode folder in your project root.

To create a launch configuration file, you can click "create a launch.json file" in the Run view, or you can open an existing file using the Command Palette. If you already have a launch.json file, you can open it using the Command Palette, and then click the Add Configuration button to add a new configuration.

Credit: youtube.com, How To Debug VSCode with Go (Golang)

There are many configuration attributes available in the launch.json file, and IntelliSense will help you navigate the options and documentation. Supported modes include Launch, which uses a launch request type configuration in your launch.json file.

For remote debugging, you'll need to add the port attribute to the launch configuration, and VS Code will connect to the external user-specified dlv dap server at host:port.

Here are some common configuration properties you can adjust using the go.delveConfig settings:

  • go.delveConfig

You can also use the language server via a configuration in settings.json, which can help you pass compile-time build flags, such as -tags foo, to the go build and go run directives. However, this may require some extra configuration and may not work perfectly.

Readers also liked: Golang Build Flags

Remote Debugging

Remote debugging is the recommended way to debug Go programs remotely in VS Code. It's a powerful tool that allows you to work with a debugger and target running on a remote machine or a container.

Credit: youtube.com, Remote Debugging Golang with dlv: Waiting for Client Connection in Visual Studio Code

You can use the Remote Development extensions and VS Code's universal remote development capabilities to enable remote debugging. Check out the Getting started section and Remote tutorials to learn more.

Remote debugging can be used on a local machine with a server started in an external terminal, making it a great option for supporting entering stdin into the server's terminal window.

With the introduction of dlv dap, users now have two options for remote debugging.

Troubleshooting

If you're having trouble setting up VSCode for GoLang debugging, it's likely due to a misconfigured launch.json file.

The launch.json file is where you define the configuration for your debugger. Make sure it's properly formatted with the correct settings, such as the runtime mode and the program arguments.

A common mistake is setting the wrong runtime mode, which can prevent the debugger from attaching to the program.

In the article, we discussed how to set up the launch.json file for a simple "hello world" program, which can help you get started with debugging.

If you're still having trouble, try checking the VSCode output for any error messages that may indicate the issue.

Remember, the launch.json file is the key to getting VSCode to work with your GoLang program.

Claire Beier

Senior Writer

Claire Beier is a seasoned writer with a passion for creating informative and engaging content. With a keen eye for detail and a talent for simplifying complex concepts, Claire has established herself as a go-to expert in the field of web development. Her articles on HTML elements have been widely praised for their clarity and accessibility.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.