env v1
The env package provides a simple way to manage environment variables in Go applications. It allows you to retrieve environment variables as different data types and handle required variables graceful
Repository
Installation
go get -u github.com/metadiv-io/env
Creating an Environment Variable
To create a new environment variable, use the New function. You can specify whether the variable is required. If a required variable is not set, the program will panic.
e := env.New("MY_ENV_VAR", true)
Methods
String()
Returns the environment variable value as a string.
value := e.String()
fmt.Println("String value:", value)
Strings()
Returns the environment variable value as a string.
value := e.String()
fmt.Println("String value:", value)
Int()
Returns the environment variable value as an integer. Returns 0 if the conversion fails.
intValue := e.Int()
fmt.Println("Integer value:", intValue)
Bool()
Returns the environment variable value as a boolean. Returns false if the conversion fails.
boolValue := e.Bool()
fmt.Println("Boolean value:", boolValue)
Float()
Returns the environment variable value as a float. Returns 0.0 if the conversion fails.
floatValue := e.Float()
fmt.Println("Float value:", floatValue)
Uint()
Returns the environment variable value as an unsigned integer. Returns 0 if the conversion fails.
uintValue := e.Uint()
fmt.Println("Unsigned integer value:", uintValue)
Example
Here's a complete example demonstrating how to use the env package:
package main
import (
"fmt"
"path/to/env"
"os"
)
func main() {
// Set an environment variable for demonstration purposes
os.Setenv("MY_ENV_VAR", "123,true,3.14")
// Create a new environment variable
e := env.New("MY_ENV_VAR", true)
// Retrieve and print the value in different formats
fmt.Println("String:", e.String())
fmt.Println("Strings:", e.Strings())
fmt.Println("Int:", e.Int())
fmt.Println("Bool:", e.Bool())
fmt.Println("Float:", e.Float())
fmt.Println("Uint:", e.Uint())
}
This example sets an environment variable MY_ENV_VAR and demonstrates how to retrieve its value in various formats using the env package.
Last updated