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 DBURL, DBNAME, USERNAME and PASSWORD in each feature. There are a few major disadvantages to this approach, there can be many.
Security Issue:
Code Management:
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.
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.
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:
- value := os.Getenv(key)
- package main
- import (
- "fmt"
- "os"
- )
- // use os package to get the env variable which is already set
- func envVariable(key string) string {
- // set env variable using os package
- os.Setenv(key, "gopher")
- // return the env variable using os package
- return os.Getenv(key)
- }
- func main() {
- // os package
- value := envVariable("name")
- fmt.Printf("os package: %s = %s \n", "name", value)
- }
GoDotEnv Package
The easiest way to load the .env file is using godotenv package.
Install
Open the terminal in the project root directory:
godotenv provides a Load method to load the env files:
- // Load the .env file in the current directory
- godotenv.Load()
- // or
- godotenv.Load(".env")
- STRONGEST_AVENGER=Thor
- package main
- import (
- "fmt"
- "os"
- "log"
- "github.com/joho/godotenv"
- )
- // use os package to get the env variable which is already set
- func envVariable(key string) string {
- // set env variable using os package
- os.Setenv(key, "gopher")
- // return the env variable using os package
- return os.Getenv(key)
- }
- // use godot package to load/read the .env file and
- // return the value of the key
- func goDotEnvVariable(key string) string {
- // load .env file
- err := godotenv.Load(".env")
- if err != nil {
- log.Fatalf("Error loading .env file")
- }
- return os.Getenv(key)
- }
- func main() {
- // os package
- value := envVariable("name")
- fmt.Printf("os package: %s = %s \n", "name", value)
- // godotenv package
- dotenv := goDotEnvVariable("STRONGEST_AVENGER")
- fmt.Printf("godotenv : %s = %s \n", "STRONGEST_AVENGER", dotenv)
- }
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.
Install
Open the terminal in the project root directory:
How to use Viper
To set the config file and path:
- viper.SetConfigFile(".env")
- viper.ReadInConfig()
- viper.Get(key)
- package main
- import (
- "fmt"
- "os"
- "log"
- "github.com/joho/godotenv"
- "github.com/spf13/viper" // <--- new import
- )
- ...
- // use viper package to read .env file
- // return the value of the key
- func viperEnvVariable(key string) string {
- // SetConfigFile explicitly defines the path, name and extension of the config file.
- // Viper will use this and not check any of the config paths.
- // .env - It will search for the .env file in the current directory
- viper.SetConfigFile(".env")
- // Find and read the config file
- err := viper.ReadInConfig()
- if err != nil {
- log.Fatalf("Error while reading config file %s", err)
- }
- // viper.Get() returns an empty interface{}
- // to get the underlying type of the key,
- // we have to do the type assertion, we know the underlying value is string
- // if we type assert to other type it will throw an error
- value, ok := viper.Get(key).(string)
- // If the type is a string then ok will be true
- // ok will make sure the program not break
- if !ok {
- log.Fatalf("Invalid type assertion")
- }
- return value
- }
- func main() {
- ...
- // viper package read .env
- viperenv := viperEnvVariable("STRONGEST_AVENGER")
- fmt.Printf("viper : %s = %s \n", "STRONGEST_AVENGER", viperenv)
- }
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.
沒有留言:
張貼留言