Skip to content Skip to sidebar Skip to footer

Unable to Read the .env Environment File

Use Surround Variable in your next Golang Project

In that location are multiple means in golang to utilise environs variables and files.

Shubham Chadokar

Photo by Moja Msanii on Unsplash

When information technology comes to creating a production-grade awarding, using the environment variable in the application is de facto.

Read my Latest articles here .

Why should we use the surroundings variable?

Suppose you lot accept an application with many features and each feature demand to admission the Database. You lot configured all the DB data similar DBURL, DBNAME, USERNAME and PASSWORD in each characteristic.

In that location are a few major disadvantages to this approach, there can be many.

Security Upshot:

  • You're inbound all the data in the lawmaking. Now, all the unauthorized person besides have access to the DB.
  • If you're using lawmaking versioning tool like git and then the details of your DB volition go public once you push the code.

Code Direction:

  • If you are irresolute a unmarried variable and then you have to modify in all the features. There is a loftier possibility that you'll miss 1 or two. 😌 been there
  • You tin categorize the environment variables like PROD, DEV, or Examination. Merely prefix the variable with the environment.

At the start, information technology might look like some extra work, simply this will reward yous a lot in your projection.

⚠️ Only don't forget to include your surround files in the .gitignore .

It is time for some action. 🔨

What are nosotros going to do in this tutorial?

In this tut o rial, we volition access environment variables in three different ways.

You lot can use according to your requirement.

  • bone parcel
  • godotenv package
  • viper package

Create a Projection

Create a project go-env-means exterior the $GOPATH .

Initialize the module

Open the last inside the project root directory, and run the beneath command.

                              get mod init go-env-ways                          

This module will go along a record of all the packages and their version used in the project. Information technology is similar to package.json in nodejs.

Let's start with the easiest i, using os package.

os Package

Golang provides bone package, an easy way to configure and admission the environs variable.

To set the environment variable,

                              os.Setenv(primal, value)                          

To get the surround variable,

                              value := os.Getenv(key)                          

Create a new file main.go inside the project.

                              bundle main                

import (
"fmt"
"bone"
)

// employ bone parcel to become the env variable which is already gear up
func envVariable(primal cord) string {

// set env variable using os package
os.Setenv(cardinal, "gopher")

// return the env variable using os package
return bone.Getenv(primal)
}

func main() {
// os package
value := envVariable("name")

fmt.Printf("os package: proper noun = %s \north", value)

fmt.Printf("environment = %south \n", os.Getenv("APP_ENV"))
}

Run the below command to cheque.

                              APP_ENV=prod go run main.go                

// Output
os package: name = gopher
environs = prod

GoDotEnv Parcel

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

Install

Open the final in the project root directory.

                              go get github.com/joho/godotenv                          

godotenv provides a Load method to load the env files.

              // Load the .env file in the current directory
godotenv.Load()

// or

godotenv.Load(".env")

Load method tin can load multiple env files at once. This besides supports yaml . For more information check out the documentation .

Create a new .env file in the project root directory.

                              STRONGEST_AVENGER=Thor                          

Update the main.go.

                              bundle primary                

import (

...
// Import godotenv
"github.com/joho/godotenv"
)

// use godot package to load/read the .env file and
// render the value of the key
func goDotEnvVariable(central string) string {

// load .env file
err := godotenv.Load(".env")

if err != cypher {
log.Fatalf("Fault loading .env file")
}

return os.Getenv(key)
}

func primary() {
// os package
...

// godotenv package
dotenv := goDotEnvVariable("STRONGEST_AVENGER")

fmt.Printf("godotenv : %southward = %s \n", "STRONGEST_AVENGER", dotenv)
}

Open the terminal and run the main.go.

                              become run primary.go                

// Output
os package: proper noun = gopher

godotenv : STRONGEST_AVENGER = Thor

Only add the code at the end of the os package in the main function.

Viper Package

Viper is one of the most pop packages in the golang community. Many Become projects are congenital using Viper including Hugo, Docker Notary, Mercury.

Viper 🐍 is a complete configuration solution for Get 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 backdrop config files

For more than information read the official documentation of viper

Install

Open the terminal in the project root directory.

                              get get github.com/spf13/viper                          

To set up the config file and path

                              viper.SetConfigFile(".env")                          

To read the config file

                              viper.ReadInConfig()                          

To get the value from the config file using cardinal

                              viper.Go(key)                          

Update the chief.go.

                              import                (
"fmt"
"log"
"os"

"github.com/joho/godotenv"
"github.com/spf13/viper"
)

// employ viper package to read .env file
// return the value of the key
func viperEnvVariable(key cord) string {

// SetConfigFile explicitly defines the path, name and extension of the config file.
// Viper will apply this and non check whatever of the config paths.
// .env - It will search for the .env file in the current directory
viper.SetConfigFile(".env")

// Detect and read the config file
err := viper.ReadInConfig()

if err != nil {
log.Fatalf("Mistake while reading config file %southward", err)
}

// viper.Become() returns an empty interface{}
// to get the underlying type of the key,
// we accept to do the blazon assertion, we know the underlying value is string
// if we blazon assert to other blazon it will throw an error
value, ok := viper.Become(key).(string)

// If the type is a string then ok volition be truthful
// ok volition make certain the program not break
if !ok {
log.Fatalf("Invalid type exclamation")
}

return value
}

func main() {

// os bundle
...

// godotenv parcel
...

// viper bundle read .env
viperenv := viperEnvVariable("STRONGEST_AVENGER")

fmt.Printf("viper : %s = %s \n", "STRONGEST_AVENGER", viperenv)
}

Open the terminal and run the main.go.

Viper is non limited to .env files.

It supports:

  • setting defaults
  • reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

Viper can exist thought of equally a registry for all of your applications configuration needs.

Let'due south experiment: 💣

Create a new config.yaml file in the project root directory.

                              I_AM_INEVITABLE: "I am Atomic number 26 Homo"                          

To set the config filename

                              viper.SetConfigName("config")                          

To prepare the config file path

              // Look in the electric current working directory                
viper.AddConfigPath(".")

To read the config file

                              viper.ReadInConfig()                          

Update the master.become

              // use viper package to load/read the config file or .env file and
// return the value of the fundamental
func viperConfigVariable(fundamental string) string {

// name of config file (without extension)
viper.SetConfigName("config")
// look for config in the working directory
viper.AddConfigPath(".")

// Find and read the config file
err := viper.ReadInConfig()

if err != cypher {
log.Fatalf("Error while reading config file %s", err)
}

// viper.Get() returns an empty interface{}
// to get the underlying type of the central,
// we have to do the blazon assertion, we know the underlying value is cord
// if we type affirm to other type it will throw an error
value, ok := viper.Become(key).(string)

// If the blazon is a cord and so ok volition be true
// ok will brand certain the plan not break
if !ok {
log.Fatalf("Invalid blazon assertion")
}

render value
}

func master() {

// os packet
...

// godotenv packet
...

// viper bundle read .env
...

// viper bundle read config file
viperconfig := viperConfigVariable("I_AM_INEVITABLE")

fmt.Printf("viper config : %south = %s \due north", "I_AM_INEVITABLE", viperconfig)
}

Open the last and run the main.go

                              go run principal.go                

// Output
os package: name = gopher

godotenv : STRONGEST_AVENGER = Thor

viper : STRONGEST_AVENGER = Thor

viper config : I_AM_INEVITABLE = I am Iron Man

Conclusion

That's it, at present you can explore more of their secrets 🔐. If yous find something worth sharing don't hesitate 😉.

The complete lawmaking is available in the GitHub.

parkerdishis.blogspot.com

Source: https://towardsdatascience.com/use-environment-variable-in-your-next-golang-project-39e17c3aaa66

Enregistrer un commentaire for "Unable to Read the .env Environment File"