Complete API documentation for the dotenv package.
Load environment variables from a file.
env, err := dotenv.Load(".env")
if err != nil {
log.Fatal(err)
}Parameters:
filename: Path to the .env file
Returns:
map[string]string: Environment variables as key-value pairserror: Error if file cannot be read or parsed
Load environment variables from any io.Reader.
env, err := dotenv.LoadFromReader(strings.NewReader("KEY=value"))Parameters:
reader: Any io.Reader containing .env content
Returns:
map[string]string: Environment variableserror: Parse or read error
Load environment variables and panic on error. Use for initialization where failure should halt execution.
env := dotenv.MustLoad(".env")Parameters:
filename: Path to the .env file
Returns:
map[string]string: Environment variables
Panics: If file cannot be loaded or parsed
Apply environment variables to the current process.
env := map[string]string{"KEY": "value"}
err := dotenv.Apply(env)Parameters:
env: Map of environment variables to set
Returns:
error: Error if any variable cannot be set
Convenience function that loads and applies environment variables in one call.
err := dotenv.LoadAndApply(".env")Parameters:
filename: Path to the .env file
Returns:
error: Load or apply error
Populate a struct with environment variables using env tags.
type Config struct {
DatabaseURL string `env:"DATABASE_URL,required"`
Port int `env:"PORT,default=8080"`
Debug bool `env:"DEBUG,default=false"`
Timeout time.Duration `env:"TIMEOUT,default=30s"`
Features []string `env:"FEATURES"`
}
var config Config
err := dotenv.Unmarshal(&config)Parameters:
v: Pointer to struct withenvtags
Returns:
error: Type conversion or validation error
Tag Format: env:"VARIABLE_NAME[,option1][,option2]"
Tag Options:
required- Field must have a value in environmentdefault=value- Default value if environment variable not set
Supported Types:
string,[]string(comma-separated values)int,int8,int16,int32,int64uint,uint8,uint16,uint32,uint64float32,float64bool(accepts: true/false, 1/0, yes/no, on/off)time.Duration(e.g., "1h", "30m", "45s")
Same as Unmarshal but adds a prefix to all environment variable names.
type Config struct {
Host string `env:"HOST"`
Port int `env:"PORT"`
}
var config Config
// Looks for MYAPP_HOST, MYAPP_PORT
err := dotenv.UnmarshalWithPrefix(&config, "MYAPP_")Parameters:
v: Pointer to struct withenvtagsprefix: String prefix to add to all variable names
Returns:
error: Type conversion or validation error
Convert a struct with env tags to a map of environment variables.
type Config struct {
DatabaseURL string `env:"DATABASE_URL"`
Port int `env:"PORT"`
Debug bool `env:"DEBUG"`
}
config := Config{
DatabaseURL: "postgresql://localhost:5432/myapp",
Port: 8080,
Debug: true,
}
env, err := dotenv.Marshal(&config)
// Returns: map[string]string{
// "DATABASE_URL": "postgresql://localhost:5432/myapp",
// "PORT": "8080",
// "DEBUG": "true",
// }Parameters:
v: Struct or pointer to struct withenvtags
Returns:
map[string]string: Environment variableserror: Marshaling error
Note: Only non-zero values are included in the output map.
Same as Marshal but adds a prefix to all environment variable names.
// Creates MYAPP_DATABASE_URL, MYAPP_PORT, etc.
env, err := dotenv.MarshalWithPrefix(&config, "MYAPP_")Parameters:
v: Struct or pointer to struct withenvtagsprefix: String prefix to add to all variable names
Returns:
map[string]string: Prefixed environment variableserror: Marshaling error
Marshal a struct directly to a .env file with proper formatting and quoting.
config := Config{Port: 8080, Debug: true}
err := dotenv.MarshalToFile("config.env", &config)Parameters:
filename: Path where .env file will be writtenv: Struct or pointer to struct withenvtags
Returns:
error: Marshaling or file write error
Output Format:
- Keys are sorted alphabetically
- Values with special characters are automatically quoted
- Proper escape sequences applied
Marshal a struct to a .env file with prefixed keys.
err := dotenv.MarshalToFileWithPrefix("db.env", &dbConfig, "DB_")Parameters:
filename: Path where .env file will be writtenv: Struct or pointer to struct withenvtagsprefix: String prefix to add to all variable names
Returns:
error: Marshaling or file write error
Write a map of environment variables to a .env file with proper quoting.
env := map[string]string{
"KEY1": "simple_value",
"KEY2": "value with spaces",
"KEY3": "value with \"quotes\" and\nnewlines",
}
err := dotenv.WriteEnvFile("output.env", env)Parameters:
filename: Path where .env file will be writtenenv: Map of environment variables
Returns:
error: File write error
Features:
- Automatic quoting for values with spaces/special characters
- Proper escape sequences (
\n,\t,\", etc.) - Sorted keys for consistent output
Type-safe functions for accessing environment variables with automatic conversion and default values.
Get environment variable as string.
host := dotenv.Env("DATABASE_HOST", "localhost")Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set
Returns: String value or default
port := dotenv.EnvInt("PORT", 8080)timeout := dotenv.EnvInt64("TIMEOUT_MS", 30000)Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set or parse fails
Returns: Integer value or default (0 if no default provided)
maxConn := dotenv.EnvUint32("MAX_CONNECTIONS", 100)Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set or parse fails
Returns: Unsigned integer value or default
pi := dotenv.EnvFloat64("PI", 3.14159)
rate := dotenv.EnvFloat32("RATE", 0.05)Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set or parse fails
Returns: Float value or default
Get environment variable as boolean.
debug := dotenv.EnvBool("DEBUG", false)Accepted Values (case-insensitive):
- True:
true,1,yes,on - False:
false,0,no,off
Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set or parse fails
Returns: Boolean value or default
Get environment variable as time.Duration.
timeout := dotenv.EnvDuration("TIMEOUT", 10*time.Second)Accepted Formats:
"1h"- hours"30m"- minutes"45s"- seconds"100ms"- milliseconds"1h30m"- combined
Parameters:
key: Environment variable namedefaultValue: Optional default if variable not set or parse fails
Returns: Duration value or default
Check if an environment variable is set.
if dotenv.HasEnv("API_KEY") {
// Variable exists
}Parameters:
key: Environment variable name
Returns: true if variable exists, false otherwise
Set an environment variable in the current process.
err := dotenv.SetEnv("NEW_VAR", "value")Parameters:
key: Environment variable namevalue: Value to set
Returns: Error if variable cannot be set
Unset an environment variable in the current process.
err := dotenv.UnsetEnv("OLD_VAR")Parameters:
key: Environment variable name
Returns: Error if variable cannot be unset
For advanced use cases requiring more control over the parsing process.
Create a new parser for the given .env content.
parser := dotenv.NewParser(content)
env, err := parser.Parse()Parameters:
content: String containing .env file content
Returns: *Parser instance
Parse the entire content and return environment variables.
parser := dotenv.NewParser(content)
env, err := parser.Parse()Returns:
map[string]string: Parsed environment variableserror: Parse error with line number
Features:
- Single-pass parsing
- Variable expansion
- Detailed error messages
Parse a single line of .env content.
parser := dotenv.NewParser(content)
for parser.tokenizer.pos < parser.tokenizer.length {
result := parser.ParseLine()
if result.Error != nil {
return result.Error
}
if result.Key != "" {
fmt.Printf("%s=%s\n", result.Key, result.Value)
}
}Returns: LineResult struct containing:
Key: Variable name (empty for blank lines/comments)Value: Variable valueAllowExpansion: Whether variable expansion is allowedError: Parse error if any
Use Cases:
- Custom parsing logic
- Line-by-line processing
- Error recovery
Result of parsing a single line.
type LineResult struct {
Key string // Variable name
Value string // Variable value
AllowExpansion bool // Whether expansion is allowed
Error error // Parse error
}Parser instance for .env content.
type Parser struct {
tokenizer *Tokenizer
}All functions that can fail return errors. Common error types:
- File Errors: File not found, permission denied
- Parse Errors: Syntax errors with line numbers
- Type Errors: Failed type conversion
- Validation Errors: Required fields missing
env, err := dotenv.Load(".env")
if err != nil {
log.Printf("Failed to load .env: %v", err)
// Handle error
}Error messages include line numbers for parse errors:
unterminated quoted string at line 5
expected '=' after variable name at line 10