我正在使用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)
}
}
envconfig.Process()用从环境变量中提取的值填充给定的结构体。可以使用envconfig
struct标签指定使用哪些环境变量。
例如:
Dbhost string `required:"true" envconfig:"DB_HOST"`
上面的代码将用DB_HOST
环境变量的值填充Dbhost
字段。如果required
标签设置为true,如果不存在匹配的环境变量,Process
将返回错误。
如果您想为不存在匹配的环境变量的情况定义默认值,则可以使用default
标记:
Dbhost string `default:"host1" envconfig:"DB_HOST"`
Process
的第一个参数是前缀,目的是只匹配具有特定前缀的环境变量。
例如:
envconfig.Process("DB", &env)
以上将只考虑带有DB_
前缀的环境变量,例如DB_HOST
、DB_PORT
、DB_USER
等。在您的特殊情况下,这将使JwtKey
和HashKey
字段未填充,因为相应的环境变量没有DB_
前缀。
我建议查看Github上的README文档,其中提供了一些更详细的解释和示例。