Skip to content

proposal: Include envconfig-style environment variable parsing in Go standard library #74558

Closed as duplicate of#64891
@mikolajsemeniuk

Description

@mikolajsemeniuk

Proposal Details

Overview

This proposal suggests adding built-in support for parsing environment variables into Go structs in the Go standard library, inspired by popular community libraries like envconfig, go-envconfig, vrischmann-envconfig. The goal is to provide a consistent, easy-to-use, and idiomatic way to load configuration from environment variables without requiring third-party dependencies.

Motivation

  • Environment variables are a widely-used mechanism for configuring Go applications, especially in cloud-native and containerized environments.
  • Currently, parsing environment variables into structs requires third-party libraries or manual boilerplate code.
  • Including a simple, flexible, and robust environment variable parser in the standard library would improve developer experience, reduce dependency management overhead, and promote best practices.

Proposed API Sketch

package env

// Load populates the fields of a struct from environment variables.
// It uses struct tags to map environment variable names and supports
// default values and required flags.
func Load(config any) error

Example usage:

var config struct {
    Port     int    `env:"PORT"      default:"8080"`
    LogLevel string `env:"LOG_LEVEL" default:"info"`
    Debug    bool   `env:"DEBUG"     required:"true"`
}

func main() {
    if err := env.Load(&config); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Config: %+v\n", config)
}

Features

  • Support for common Go types (string, int, bool, float64, etc.)
  • Custom struct tags to specify environment variable names (env), default values (default), and required fields (required)
  • Support for nested structs and slices
  • Clear error reporting for missing required variables or parsing errors
  • Optionally allow custom parsing hooks

Alternatives Considered

  • Relying on existing popular libraries (envconfig, godotenv, viper, etc.) — while powerful, they introduce external dependencies and API variations.
  • Manually parsing environment variables — leads to repetitive, error-prone code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions