侧边栏壁纸
博主头像
里奥的博客博主等级

行动起来,活在当下

  • 累计撰写 24 篇文章
  • 累计创建 7 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

VS Code调试golang加载环境变量

里奥
2024-05-14 / 0 评论 / 1 点赞 / 75 阅读 / 3117 字

问题

使用VS Code调试golang时需要预先加载一个.env的环境变量文件, 怎样配置VS Code 才能加载这个文件?

如下图示,项目中有个环境变量的配置文件, 在调试时需要先将它加载出来

在代码里需要用到这些环境变量

解决方法

修改launch.json配置文件, 在配置文件中设置envFile属性. 如下所示.

  1. 点击Run and Debug 按钮

  2. 点击小齿轮按钮,打开launch.json配置文件

  3. 修改envFile属性, 设置为 "envFile": "${workspaceFolder}/.env" 如下图示

下面为参考配置

{
    // 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",
            "type": "go",
            "request": "launch",
            // "mode": "auto",
            "mode": "debug",
            "cwd": "${workspaceFolder}",
            "program": "${workspaceFolder}",
            "envFile": "${workspaceFolder}/.env",
            // "showGlobalVariables": true
        }
    ]
}

可以参考官方文档

注意事项

环境变量文件.env 不可以写成下面这个样子,也就是不能添加export 只能是键值对的形式出现

参考文档

  1. How To Debug Go Code with Visual Studio Code | DigitalOcean

  2. https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes

  3. https://github.com/bnchrch/reverse-proxy-demo

1

评论区