Skip to content

Go libraries, Open source

xEnv

Environment variable management for Go

A Go library that checks your environment variables and loads them from a .env file.

environments.go from the xEnv README typed into an editor: an Env struct with HOST and ADMIN_EMAIL validators, and an init function that calls xenv.LoadEnvFile(".env") and xenv.ValidateEnv(&Env), with the go get command below.
Load and validate .env at startup

Stack

  • Go
  • Open source
  • Library
Status
Open source
Type
Go libraries
Source
GitHub

The problem

Go has no built-in way to load a .env file, and a missing or wrong variable can break a launch.

What it does

xEnv manages environment variables in Go applications. It checks that every variable is set correctly and loads values from a .env file, which Go does not support by default. Its behavior is customizable.

How it's built

A Go library, open source on GitHub.

Key features

  • Loads variables from a .env file (xenv.LoadEnvFile)
  • Validates variables against rules in struct tags: required, minLength, maxLength, email (xenv.ValidateEnv)
  • Run both in init() to stop the app at startup when a variable is missing or invalid
  • Customizable to your needs

Install and usage

Install

go get github.com/dev3mike/go-xenv
Keep the configuration in a dedicated file, for example environments/environments.go

go

package environments

import (
    "github.com/dev3mike/go-xenv"
    "log"
)

var Env struct {
    Host       string `json:"HOST" validators:"required,minLength:3,maxLength:50"`
    AdminEmail string `json:"ADMIN_EMAIL" validators:"email"`
}

func init() {
    // Load environment variables from a .env file
    if err := xenv.LoadEnvFile(".env"); err != nil {
        log.Panic("Error loading .env file: ", err)
    }

    // Validate environment variables
    if err := xenv.ValidateEnv(&Env); err != nil {
        log.Panic("Failed to validate environment: ", err)
    }

    log.Println("Environment validated successfully!")
}
  • xEnv README code: an Environment struct whose HOST and ADMIN_EMAIL fields use validators and the trim and lowercase transformers, and a main function reading the validated values from environments.Env.
    Transformers and typed access

Contact

Want something like this built?