lazyenv

package module
v0.0.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2024 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package lazyenv provides easy access to the environment

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Env

func Env() string

Env returns Development if the environment is a terminal or the ENVIRONMENT variable starts with "dev". If the environment variable does not starts with dev, it will assume it is development if the output is a terminal. Otherwise it will return Production. Env can only return the strings "development" or "production". If you want to access the environment directly, use os.Getenv("ENVIRONMENT")

func Fill

func Fill(dest interface{})

Fill fills the fields of the struct with the values from the environment. It will use the uppercase and dash separated name of the field as the environment variable name. For example, if the struct has a field named "DBName", it will look for the environment variable "DB_NAME". It will try to convert the value to the type of the field. If the field is a pointer, it will try to convert the value to the type of the pointer. If the field is a slice, it will split the value by commas. If the field is a map, it will split the value by commas and then by colons. If the field is a struct, it will recursively fill the fields of the struct using the field name as a prefix. The name of the environment variable can be overridden by the "env" tag in the struct field.

Example
os.Setenv("DB_NAME", "test_db")
os.Setenv("DB_HOST", "localhost")
os.Setenv("DB_PASS", "localhost")
os.Setenv("USER_ID", "42")
os.Setenv("HTTP_SERVER", "localhost")
os.Setenv("SIMPLE", "true")
os.Setenv("ANOTHER", "1,2,3")
os.Setenv("MAP_EXAMPLE", "key1:value1,key2:value2")
os.Setenv("lowercase", "with_env")

type Config struct {
	DB struct {
		Name     string
		Host     string
		Password string `env:"PASS"`
	}
	UserID     int
	HTTPServer string
	Simple     bool
	Another    []int
	MapExample map[string]string
	LowerCase  string `env:"lowercase"`
}

var config Config
Fill(&config)

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

{DB:{Name:test_db Host:localhost Password:localhost} UserID:42 HTTPServer:localhost Simple:true Another:[1 2 3] MapExample:map[key1:value1 key2:value2] LowerCase:with_env}

func IsDevelopment

func IsDevelopment() bool

IsDevelopment returns true if the environment is development

func IsProduction

func IsProduction() bool

IsProduction returns true if the environment is production

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳