VSCode wrong path while debugging Go program

Viewed 3312

I have my main.go in a subfolder cmd/admin/main.go but when I'm debugging and there are errors in a file, it gives me the relative path from the main.go folder instead of the workspace folder. So for example I will have the error ..\..\path\to\file.go:238:3: undefined: test which won't work if I try to Ctrl+click it.
If I launch the command from the root go run cmd/admin/main.go that works as intended returning path\to\file.go:238:3: undefined: test.

My launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch",
      "mode": "auto",
      "cwd": "${workspaceFolder}",
      "program": "${workspaceFolder}/cmd/admin",
      "env": {},
      "args": []
    }
  ]
}

Go version 1.16.6
VSC version 1.58.2
OS Windows10

2 Answers

Go File > Add Folder to Workspace Then select the folders containing main.go enter image description here You can also do it in the command line:

code cmd/admin -a

Now make sure your current launch.json has been deleted to start fresh, your workspace should look like this:

enter image description here

Notice that there is a 'package main' and 'func main()' this is required for Go to know the entry point.

Now press Run and Debug with a breakpoint:

enter image description here

That's it, it should now work on any folders you add to your workspace. If you want more specific debug options, add them to your workspace and they'll apply in the context of the file you run from. Click the 'create a launch.json file.:

enter image description here

Select workspace:

enter image description here

Select Go: Launch package

enter image description here

You now have a launch config that will apply to the directory you run it from:

enter image description here

Make sure to save your workspace to keep it:

enter image description here

Notes

  • Be sure to delete your current launch.json files if they already exist anywhere.

  • Make sure all of your source code is located in GOPATH/src, you can find out where GOPATH is by putting this into a command line:

go env GOPATH

More info

VS Code workspace debugging: https://code.visualstudio.com/docs/editor/multi-root-workspaces#_debugging

GOPATH: https://golang.org/doc/gopath_code

Try and make sure:

  • you have no GOxxx environment variable set (no GO_BASE_PATH, no GOROOT), except for GOPATH set to %USERPROFILE%\go, and %GOPATH%\bin in your %PATH%
  • you are using Go installed in the default C:\Program Files\Go\ folder
  • you have set up your project using Go modules, with a go mod init myproject
  • you have defined a multi-root workspace for your project root folder, compose of only one root: your project. Save that workspace (it will create a <name>.code-workspace JSON file).

See then if the issue persists (and no cwd should be needed in your launch.json)

Related