2020年8月1日 星期六

[ 文章收集 ] Use Environment Variable in your next Golang Project

Source From Here
Preface
When it comes to creating a production-grade application, using the environment variable in the application is.

Why should we use the environment variable?
Suppose you have an application with many features and each feature need to access the Database. You configured all the DB information like DBURLDBNAMEUSERNAME and PASSWORD in each feature. There are a few major disadvantages to this approach, there can be many.

Security Issue:
* You’re entering all the information in the code. Now, all the unauthorized person also have access to the DB.
* If you’re using code versioning tool like git then the details of your DB will go public once you push the code.

Code Management:
* If you are changing a single variable then you have to change in all the features. There is a high possibility that you’ll miss one or two.
* You can categorize the environment variables like PROD, DEV, or TEST. Just prefix the variable with the environment.

At the start, it might look like some extra work, but this will reward you a lot in your project.

What are we going to do in this tutorial?
In this tutorial, we will access environment variables in 3 different ways. You can use according to your requirement.
os package
godotenv package
viper package

Create a Project
Create a project go-env-ways outside the $GOPATH.

Initialize the module
Open the terminal inside the project root directory, and run the below command.
# go mod init go-env-ways

This module will keep a record of all the packages and their version used in the project. It is similar to package.json in nodejs. Let’s start with the easiest one, using os package.

os Package
Golang provides os package, an easy way to configure and access the environment variable. To set the environment variable by os.Setenv(key, value); To get the environment variable:
  1. value := os.Getenv(key)  
Create a new file main.go inside the project:
  1. package main  
  2.   
  3. import (  
  4.   "fmt"  
  5.   "os"  
  6. )  
  7.   
  8. // use os package to get the env variable which is already set  
  9. func envVariable(key string) string {  
  10.   
  11.   // set env variable using os package  
  12.   os.Setenv(key, "gopher")  
  13.   
  14.   // return the env variable using os package  
  15.   return os.Getenv(key)  
  16. }  
  17.   
  18. func main() {  
  19.   // os package  
  20.   value := envVariable("name")  
  21.   
  22.   fmt.Printf("os package: %s = %s \n""name", value)  
  23. }  
Run the below command to check:
# go run go-env-ways/main.go
os package: name = gopher

GoDotEnv Package
The easiest way to load the .env file is using godotenv package.

Install
Open the terminal in the project root directory:
# go get github.com/joho/godotenv

godotenv provides a Load method to load the env files:
  1. // Load the .env file in the current directory  
  2. godotenv.Load()  
  3.   
  4. // or  
  5. godotenv.Load(".env")  
Load method can load multiple env files at once. This also supports yaml. For more information check out the documentation. Create a new .env file in the project root directory:
  1. STRONGEST_AVENGER=Thor  
Update the main.go:
  1. package main  
  2.   
  3. import (  
  4.   "fmt"  
  5.   "os"  
  6.   "log"  
  7.   "github.com/joho/godotenv"  
  8. )  
  9.   
  10. // use os package to get the env variable which is already set  
  11. func envVariable(key string) string {  
  12.   
  13.   // set env variable using os package  
  14.   os.Setenv(key, "gopher")  
  15.   
  16.   // return the env variable using os package  
  17.   return os.Getenv(key)  
  18. }  
  19.   
  20. // use godot package to load/read the .env file and  
  21. // return the value of the key  
  22. func goDotEnvVariable(key string) string {  
  23.   
  24.   // load .env file  
  25.   err := godotenv.Load(".env")  
  26.   
  27.   if err != nil {  
  28.     log.Fatalf("Error loading .env file")  
  29.   }  
  30.   
  31.   return os.Getenv(key)  
  32. }  
  33.   
  34. func main() {  
  35.   // os package  
  36.   value := envVariable("name")  
  37.   
  38.   fmt.Printf("os package: %s = %s \n""name", value)  
  39.   
  40.   // godotenv package  
  41.   dotenv := goDotEnvVariable("STRONGEST_AVENGER")  
  42.   
  43.   fmt.Printf("godotenv : %s = %s \n""STRONGEST_AVENGER", dotenv)  
  44. }  
Open the terminal and run the main.go.
# go run main.go
os package: name = gopher
godotenv : STRONGEST_AVENGER = Thor

Viper Package
Viper is one of the most popular packages in the golang community. Many Go projects are built using Viper including Hugo, Docker Notary, Mercury.
Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application and can handle all types of configuration needs and formats. Reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
For more information read the official documentation of viper

Install
Open the terminal in the project root directory:
# go get github.com/spf13/viper

How to use Viper
To set the config file and path:
  1. viper.SetConfigFile(".env")  
To read the config file
  1. viper.ReadInConfig()  
To get the value from the config file using key
Update the main.go:
  1. package main  
  2.   
  3. import (  
  4.   "fmt"  
  5.   "os"  
  6.   "log"  
  7.   "github.com/joho/godotenv"  
  8.   "github.com/spf13/viper"   // <--- new import  
  9. )  
  10.   
  11. ...  
  12. // use viper package to read .env file  
  13. // return the value of the key  
  14. func viperEnvVariable(key string) string {  
  15.   
  16.   // SetConfigFile explicitly defines the path, name and extension of the config file.  
  17.   // Viper will use this and not check any of the config paths.  
  18.   // .env - It will search for the .env file in the current directory  
  19.   viper.SetConfigFile(".env")  
  20.   
  21.   // Find and read the config file  
  22.   err := viper.ReadInConfig()  
  23.   
  24.   if err != nil {  
  25.     log.Fatalf("Error while reading config file %s", err)  
  26.   }  
  27.   
  28.   // viper.Get() returns an empty interface{}  
  29.   // to get the underlying type of the key,  
  30.   // we have to do the type assertion, we know the underlying value is string  
  31.   // if we type assert to other type it will throw an error  
  32.   value, ok := viper.Get(key).(string)  
  33.   
  34.   // If the type is a string then ok will be true  
  35.   // ok will make sure the program not break  
  36.   if !ok {  
  37.     log.Fatalf("Invalid type assertion")  
  38.   }  
  39.   
  40.   return value  
  41. }  
  42.   
  43. func main() {  
  44.   ...  
  45.   
  46.   // viper package read .env  
  47.   viperenv := viperEnvVariable("STRONGEST_AVENGER")  
  48.   
  49.   fmt.Printf("viper : %s = %s \n""STRONGEST_AVENGER", viperenv)  
  50. }  
Open the terminal and run the main.go.
# go run main.go
os package: name = gopher
godotenv : STRONGEST_AVENGER = Thor
viper : STRONGEST_AVENGER = Thor

Conclusion
That’s it, now you can explore more of their secrets . If you find something worth sharing don’t hesitate .The complete code is available in the GitHub.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...