我正在使用 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,則在不存在匹配的環境變量時將返回錯誤。Dbhost
DB_HOST
required
Process
如果要為不匹配的環境變量不存在的情況定義默認值,則可以使用 標記:default
Dbhost string `default:"host1" envconfig:"DB_HOST"`
第一個參數 to 是前綴,以便僅將環境變量與特定前綴匹配。Process
例如:
envconfig.Process("DB", &env)
以上將僅考慮具有前綴的環境變量,例如 , , 等。在您的特定情況下,這將使字段保持未填充狀態,因為相應的環境變量沒有前綴。DB_
DB_HOST
DB_PORT
DB_USER
JwtKey
HashKey
DB_
我建議查看Github上的自述文件文檔,其中提供了一些更詳細的解釋和示例。
- 1 回答
- 0 關注
- 96 瀏覽
添加回答
舉報
0/150
提交
取消