因為工作關係開始使用 Golang 進行開發工作,正好遇到存取環境變數需求,趁這個機會簡單彙整一下相關語法,除了自己做筆記,也讓有需要的朋友參考。
Golang 透過 os 套件,讓開發人員可以對系統環境變數進行操作,只需要在程式上方 import os 即可 (為Golang 主要套件,無須額外下載)。設定與取用環境變數相當簡單:
設定: os.SetEnv("變數名稱","變數值")
取用: os.Getenv("變數名稱")
簡單的範例如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
os.Setenv("EnvName", "1") | |
fmt.Println("EnvName:", os.Getenv("EnvName")) | |
} |
執行結果如下:
另一方面,你可以透過下列指令列出所有環境變數 (取存為陣列,你需要搭配迴圈使用)
os.Environ()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
for _, env := range os.Environ() { | |
fmt.Println(env) | |
} | |
} |
執行結果如下:
若您需要在執行過程中,清除所有環境變數,只需要使用 os.clearenv() 指令。理所當然,當您執行程式的時候,將不會印出任何內容。到此為止,即是 Golang 對環境變數操作的指令說明,希望這篇文章對您有所幫助。
0 留言