Debugging go in vscode with environment variables

Reuven Harrison
2 min readJul 8, 2018

When running tests in vscode you often need environment variables, some of which may have json values.

Option 1: settings.json

Open settings.json and add this at the top level:

"go.testEnvVars": {
"LOG_LEVEL": "debug",
},

All your tests will now receive this environment variable.

Option 2: launch.json

To start, you need to configure launch.json:

{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${workspaceFolder}",
"args": [],
"showLog": true
}
]
}

Note that this will try to debug code in your root directory.
If you have subdirs in your project, you will need something like this:

“program”: “${workspaceFolder}/subdir”

Or specify the source file and, optionally, the test function name:

"program": "${workspaceFolder}/subdir/http_test.go",
"args": [
"-test.run",
"TestWithHTTP"
]

Now you can add environment variables in launch.json:

{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"${workspaceFolder}/subdir/http_test.go",
"args": [
"-test.run",
"TestWithHTTP"
],
"env": {
"GCLOUD_PROJECT_ID":"my-project"
},
"showLog": true
}
]
}

For more advanced scenarios, for example, requiring json values, you can load an external environment file, like this:

{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"${workspaceFolder}/subdir/http_test.go",
"args": [
"-test.run",
"TestWithHTTP"
],
"envFile": "${workspaceFolder}/.env",
"showLog": true
}
]
}

Place the .env file in your directory and add more variables like this:

KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'

Running Your Tests

Getting VSCode to actually use the environment vars is tricky.
This seems to work:

  • Write a test function like this:
  • Don’t click “run test” nor “debug test” — these won’t leverage your environment.
  • Instead, click the View menu and select Debug (or ctrl+shift+d)
  • Select the name of your configuration in the DEBUG drop-down and click the Green “run” arrow — this will run your test in debug mode with the environment that you defined:

You can find some additional information here:

https://github.com/Microsoft/vscode-go/wiki/Debugging-Go-code-using-VS-Code

--

--