keitaro1020 / go-env

go-env is a library in Go that maps environment variables to structs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

go-env

<keitaro1020> codecov

go-env is a library in Go that maps environment variables to structs.

Usage

install

$ go get -u github.com/keitaro1020/go-env

environment variables

export PRODUCTION=true
export DATABASE_HOST=127.0.0.1
export DATABASE_PORT=3306
export DATABASE_USER=root
export DATABASE_PASS=password

writing code

package main

import (
	"fmt"

	"github.com/keitaro1020/go-env"
)

type Config struct {
	Production bool
	DBConfig   DatabaseConfig `env_key:"DATABASE"`
}

type DatabaseConfig struct {
	Host string
	Port int
	User string
	Pass string
}

func main() {
	cfg := &Config{}
	if err := env.Parse(cfg); err != nil {
		fmt.Errorf("error: %v\n", err)
	}
	fmt.Printf("cfg: %+v\n", cfg)
}

run

$ go run main.go     
cfg: &{Production:true DBConfig:{Host:127.0.0.1 Port:3306 User:root Pass:password}}

Supported types

  • string
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • bool
  • slices of any supported type

About

go-env is a library in Go that maps environment variables to structs.

License:MIT License


Languages

Language:Go 98.4%Language:Makefile 1.6%