VSCode, also known as Visual Studio Code, is a highly versatile and feature-rich code editor that has won the hearts of developers worldwide. With its clean and intuitive interface, it provides a delightful coding experience, making it a top choice for many professionals and enthusiasts alike.
In a previous article of mine, we saw how to configure useful user snippets. Now I want to explore its debugging capabilities.
In this short article, we'll see how to debug a CLI app written in Golang.
Here's our very simple app, which takes command-line arguments:
cmd/main.go
package main
import (
"fmt"
"os"
"github.com/jessevdk/go-flags"
)
var opts struct {
Name string `short:"n" long:"name" description:"name" required:"true"`
Age int `short:"a" long:"age" description:"age" required:"true"`
Email string `short:"e" long:"email" description:"email" required:"true"`
}
func run(args []string) {
flags.ParseArgs(&opts, args)
fmt.Printf("opts.Name: %v\n", opts.Name)
fmt.Printf("opts.Age: %v\n", opts.Age)
fmt.Printf("opts.Email: %v\n", opts.Email)
}
func main() {
run(os.Args)
}
Once again, as I did in this article about Golang, Kafka, and MongoDB real-time data processing, I'm using github.com/jessevdk/go-flags instead of the core flag package since it has several advantages.
To run it, we do:
$ go run cmd/main.go --name Tiago --age 39 --email [email protected]
Name: Tiago
Age: 39
Email: [email protected]
Nice. Of course, we're not doing anything useful in this simple app. But what if we have a complex CLI app and need to debug it?
In VSCode, click on "Run and Debug" and then "create a launch.json file":
Next, select "Go: Launch Package" option and hit enter:
Then, we'll replace the sample JSON with this one:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "cmd/main.go",
"args": [
"--name",
"Tiago",
"--age",
"39",
"--email",
"[email protected]"
]
}
]
}
When you save it, the "Run and Debug" view will look like this:
Now let's come back to our `cmd/main.go` file and put a break point:
Similarly to other IDEs, you put a break point by double-clicking on the left side of the line number.
Now, back to "Run and Debug" view; just click on the green play icon:
Then the little debug toolbar will be displayed, enabling us to continue, step over, step into, step out, restart, and stop the debugging session. We'll see the output in "debug console.”