我正在使用 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)
}
}
一只斗牛犬
喵喵时光机
随时随地看视频慕课网APP
相关分类