首页 > 解决方案 > 有没有办法在 golang 中实现这样的目标?

问题描述

当前代码如下所示(简化版)。

const (
    loginURL        = "http://test.xxx.com"
    authURL         = "http://test.xxx.com"
    tokenURL        = "http://test.xxx.com"
)
err := login(loginURL)
err = auth(authURL)
err = token(tokenURL)

现在我想根据不同的情况更改 URL。

const test(
    loginURL        = "http://test.xxx.com"
    authURL         = "http://test.xxx.com"
    tokenURL        = "http://test.xxx.com"
) // test block


const dev(
    loginURL        = "http://dev.xxx.com"
    authURL         = "http://dev.xxx.com"
    tokenURL        = "http://dev.xxx.com"
) // dev block

// if test, use test URLs; if dev, use dev URLs.

err := login(loginURL)
err = auth(authURL)
err = token(tokenURL)

有没有办法实现上述目标?还是更好的方法?

标签: go

解决方案


我建议您为此使用环境变量

var (
    loginURL        = os.Getenv("LOGIN_URL")
    authURL         = os.Getenv("AUTH_URL")
    tokenURL        = os.Getenv("TOKEN_URL")
)
err := login(loginURL)
err = auth(authURL)
err = token(tokenURL)

推荐阅读