Mastering Go Application Debugging with Visual Studio Code

Debugging is an essential part of the software development process, allowing developers to identify and fix errors in their code before it reaches production. However, when working with complex, interconnected modules, debugging can become a daunting task. Fortunately, Visual Studio Code (VS Code) provides an excellent solution for debugging Go applications, making it easier to detect and resolve issues.

Getting Started

To follow along with this tutorial, you’ll need:

  • Go installed on your system
  • Basic understanding of the Go programming language
  • VS Code v1.63 installed on your computer
  • Go and Delve extensions installed in your VS Code editor

Creating a Sample App

Let’s create a basic Go application that generates a JSON output from an array. Open your terminal and run the following commands:


go mod init github.com/USERNAME/sample-app
go get -u github.com/davecgh/go-spew/spew

Replace USERNAME with your personal GitHub username. Open the main.go file and add the following code:

“`go
package main

import (
“encoding/json”
“fmt”
)

type userinfo struct {
Name string
Email string
}

func main() {
userinfos := []userinfo{
{“John Doe”, “[email protected]”},
{“Jane Doe”, “[email protected]”},
{“Richard Roe”, “[email protected]”},
}

jsonData, err := json.Marshal(userinfos)
if err!= nil {
    fmt.Println(err)
    return
}

fmt.Println(string(jsonData))

}
“`

This code will print the userinfos array in JSON format. You can execute the application using the following command:


go run main.go

Setting Up a Debugging Session

Setting up the debugging configuration in Go is straightforward. From your VS Code’s sidebar menu, click on the Run and Debug button, then click on create a launch.json file. Select your workspace folder, then select Go for environment language, and finally, select Launch Package for debug configuration.

Debugging Using Breakpoints

Breakpoints allow you to inspect a line of code by pausing its execution. Let’s add breakpoints to lines 26, 29, and 35. Simply click to the left of the line number, and you’ll see a red dot appear. When you debug the program, execution will pause at each breakpoint.

Inspecting Code Execution

The debug toolbar contains directions for effectively navigating the debugger. You can use the Continue button to resume the program’s execution when it pauses at a breakpoint. The Step Over command runs the line of code that is currently highlighted before moving on to the next line. The Step Into command allows you to debug a program line-by-line, entering functions as needed. The Step Out command continues the current function’s execution, pausing at the last line.

Debugging Using Unit Testing

Unit testing helps ensure that each component of the application performs its intended function properly. Let’s look at how we can debug a Go application using unit testing in VS Code. Create a test file named main_test.go and add the following code:

“`go
package main

import (
“testing”
)

func Test_average(t *testing.T) {
numbers := []int{10, 20, 30}
average := calculateAverage(numbers)
if average!= 20 {
t.Errorf(“Expected average to be 20, but got %f”, average)
}
}

func calculateAverage(numbers []int) float64 {
sum := 0
for _, num := range numbers {
sum += num
}
return float64(sum) / float64(len(numbers))
}
“`

To run the unit test, enter the following command:


go test -v main_test.go

Now you can start the debugging session, then use the Debug Tool to step over and inspect each variable and change their value under the variables section.

Conclusion

In this article, we covered the fundamentals of debugging Go applications with Visual Studio Code. The VS Code editor offers helpful plugins that make debugging easy. We can add breakpoints, conditional breakpoints, and logpoints to pause our code execution, allowing us to deeply inspect what went wrong. We also explored some of the shortcuts available in the debug toolbar, which allow us to navigate through our code during the debugging process.

Leave a Reply

Your email address will not be published. Required fields are marked *