How to Debug Golang with VS Code

Summary

Basic

Spec

Instruction

MacOS

  1. install go : brew install golang
  2. add go/bin to PATH
  3. install extension “Go”
  4. install other tools: F1->Go: Install/Update Tools

Windows

  1. install go and add go/bin to PATH
  2. install extension “Go”
  3. install other tools: F1->Go: Install/Update Tools

Linux

  1. install go and add go/bin to PATH
  2. install extension “Go”
  3. install other tools: F1->Go: Install/Update Tools

unit test

source : bubbleSort_test.go

inline

inline unit test

launch json

menu:Go: Launch test function

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch test function",
      "type": "go",
      "request": "launch",
      "mode": "test",
      "program": "${workspaceFolder}",
      "args": [
        "-test.run",
        // test function name
        // * can use reguler expression
        // * NOT include "Test"
        // * the first charactor MUST be small
        "bubblesort"
      ]
    }
  ]
}

using Test Explorer

install Go Test Explorer

ext install ethan-reesor.vscode-go-test-adapter

debugging executable file

source: bubblesorter/cmd/bubblesorter/bubbleSorter.go

launch.json

menu:Go: Launch package

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Package",
      "type": "go",
      "request": "launch",
      "mode": "debug",
      "program": "${workspaceFolder}/bubblesorter/cmd/bubbleSorter"
    }
  ]
}

start debugging

▶︎ Launch Package

debugging local process

source: bubblesorter/cmd/bubblesorter/bubbleSorter.go

prepare

# build executable file
cd bubblesorter/cmd/bubblesorter
go build

# enable ptrace scope (for Linux)
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

start process

./bubblesorter -sleep 30 7 4 2 6 &

[1] 1859211

edit launch.json

Add processId to launch.json.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach local process",
      "type": "go",
      "request": "attach",
      "mode": "local",
      "processId": 1859211,
      "apiVersion": 2,
      "showLog": true
    }
  ]
}

start debugging

▶︎ Attach local process

debugging running remote process

prepare

cd cmd/bubbleSorter/
go build

# enable ptrace scope (for Linux)
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

execute and dlv attach

cd cmd/bubbleSorter/

# runnning process
./bubbleSorter -sleep 30 &
PID=$!
dlv attach $PID ./bubbleSorter --headless --listen=0.0.0.0:2345 --log --api-version 2

edit launch.json

Edit host to remote server address.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach remote process",
      "type": "go",
      "request": "attach",
      "mode": "remote",
      "port": 2345,
      "host": "127.0.0.1",
      "apiVersion": 2,
      "showLog": true
    }
  ]
}

start debugging

▶︎ Attach remote process