为了账号安全,请及时绑定邮箱和手机立即绑定

羡慕什么。进程() 做

羡慕什么。进程() 做

Go
一只斗牛犬 2022-09-26 15:49:16
我正在使用 envconfig 库浏览一些源代码,但无法理解以下代码的作用。我知道它加载环境变量,但想了解每条特定行的作用。我希望有人能向我解释一下。特别是生产线的作用envconfig.Process("", &Env) package config      import (        "html/template"        "log"        "os"            "github.com/joho/godotenv"        "github.com/kelseyhightower/envconfig"    )        type envVars struct {        Dbhost     string `required:"true" envconfig:"DB_HOST"`        Dbport     string `required:"true" envconfig:"DB_PORT"`        Dbuser     string `required:"true" envconfig:"DB_USER"`        Dbpassword string `required:"true" envconfig:"DB_PASS"`        Dbname     string `required:"true" envconfig:"DB_NAME"`        JwtKey     string `required:"true" envconfig:"JWT_KEY"`        HashKey    string `required:"true" envconfig:"HASH_KEY"`    }        //Env holds application config variables    var Env envVars        // Tpl template    var Tpl *template.Template        func init() {            wd, err := os.Getwd() //get path of working directory(current directory) - directory of this project        if err != nil {            log.Println(err, "::Unable to get paths")        }            Tpl = template.Must(template.ParseGlob(wd + "/internal/views/*.html")) //could use path.join in case it's used on linux instead of windows.                    //load .env file        err = godotenv.Load(wd + "/./.env") //loads environment variable file so that env variables can be accessed in code eg. by using os.GetEnv("DB_DIALECT"), won't work otherwise.            if err != nil {            log.Println("Error loading .env file, falling back to cli passed env")        }            err = envconfig.Process("", &Env)            if err != nil {            log.Fatalln("Error loading environment variables", err)        }        }
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

羡慕。Process() 使用从环境变量中提取的值填充给定的结构。可以使用结构标记指定使用哪些环境变量。envconfig

例如:

Dbhost     string `required:"true" envconfig:"DB_HOST"`

以上内容将使用环境变量的值填充字段。如果标记设置为 true,则在不存在匹配的环境变量时将返回错误。DbhostDB_HOSTrequiredProcess

如果要为不匹配的环境变量不存在的情况定义默认值,则可以使用 标记:default

Dbhost     string `default:"host1" envconfig:"DB_HOST"`

第一个参数 to 是前缀,以便仅将环境变量与特定前缀匹配。Process

例如:

envconfig.Process("DB", &env)

以上将仅考虑具有前缀的环境变量,例如 , , 等。在您的特定情况下,这将使字段保持未填充状态,因为相应的环境变量没有前缀。DB_DB_HOSTDB_PORTDB_USERJwtKeyHashKeyDB_

我建议查看Github上的自述文件文档,其中提供了一些更详细的解释和示例。


查看完整回答
反对 回复 2022-09-26
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信