亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

羨慕什么。進程() 做

羨慕什么。進程() 做

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 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號