普通网友 2016-10-30 06:21
浏览 77
已采纳

如果env var为空,如何分配默认值?

How do you assign a default value if an environment variable isn't set in Go?

In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass') where pass is the default value if MONGO_PASS env var isn't set.

I tried an if statement based on os.Getenv being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.

  • 写回答

6条回答 默认 最新

  • douba1498 2016-10-30 06:30
    关注

    There's no built-in to fall back to a default value, so you have to do a good old-fashioned if-else.

    But you can always create a helper function to make that easier:

    func getenv(key, fallback string) string {
        value := os.Getenv(key)
        if len(value) == 0 {
            return fallback
        }
        return value
    }
    

    Note that as @michael-hausenblas pointed out in a comment, keep in mind that if the value of the environment variable is really empty, you will get the fallback value instead.

    Even better as @ŁukaszWojciechowski pointed out, using os.LookupEnv:

    func getEnv(key, fallback string) string {
        if value, ok := os.LookupEnv(key); ok {
            return value
        }
        return fallback
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA