Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var DefaultBinder = &Binder{TagKey: "env"}
DefaultBinder uses `env` as TagKey
Functions ¶
func Bind ¶ added in v0.1.0
func Bind(dst interface{}) error
Bind binds environment variables to dst by DefaultBinder
Example ¶
package main
import (
"fmt"
"os"
"time"
"github.com/proproto/goenv"
)
func main() {
type config struct {
Host string `env:"HOST,required"`
Skip string `env:"-"`
ReadTimeout time.Duration `env:""`
WriteTimeout time.Duration
}
os.Clearenv()
os.Setenv("HOST", "0.0.0.0")
os.Setenv("SKIP", "SHOULD_NOT_PRESENT")
os.Setenv("READ_TIMEOUT", "1s")
os.Setenv("WRITE_TIMEOUT", "2s")
c := config{}
err := goenv.Bind(&c)
fmt.Println("err:", err)
fmt.Println("Host:", c.Host)
fmt.Printf("Skip: '%s'\n", c.Skip)
fmt.Println("ReadTimeout:", c.ReadTimeout.String())
fmt.Println("WriteTimeout:", c.WriteTimeout.String())
}
Output: err: <nil> Host: 0.0.0.0 Skip: '' ReadTimeout: 1s WriteTimeout: 2s
Example (Error) ¶
package main
import (
"fmt"
"os"
"github.com/proproto/goenv"
)
func main() {
type config struct {
Host string `env:"HOST,required"`
}
os.Clearenv()
c := config{}
err := goenv.Bind(&c)
fmt.Println(err)
}
Output: goenv: HOST not set
func MustBind ¶ added in v0.1.0
func MustBind(dst interface{})
MustBind binds environment variables to dst by DefaultBinder if fails, it would panic
Example ¶
package main
import (
"fmt"
"os"
"time"
"github.com/proproto/goenv"
)
func main() {
type MySQLConfig struct {
Host string `env:"MYSQL_HOST,default=localhost:3306"`
User string `env:"MYSQL_USER,default=root"`
Password string `env:"MYSQL_PASSWORD"`
Database string `env:"MYSQL_DATABASE,required"`
Timeout time.Duration `env:"MYSQL_TIMEOUT,default=10s"`
TLS bool `env:"MYSQL_TLS_ENABLED"`
MaxConns int `env:"MYSQL_MAX_CONNS"`
}
config := MySQLConfig{}
os.Clearenv()
os.Setenv("MYSQL_PASSWORD", "db_password")
os.Setenv("MYSQL_DATABASE", "db_name")
os.Setenv("MYSQL_TLS_ENABLED", "true")
os.Setenv("MYSQL_MAX_CONNS", "32")
goenv.MustBind(&config)
fmt.Printf("Host: %s\n", config.Host)
fmt.Printf("User: %s\n", config.User)
fmt.Printf("Password: %s\n", config.Password)
fmt.Printf("Database: %s\n", config.Database)
fmt.Printf("Timeout: %v\n", config.Timeout.String())
fmt.Printf("TLS: %v\n", config.TLS)
fmt.Printf("MaxConns: %v\n", config.MaxConns)
}
Output: Host: localhost:3306 User: root Password: db_password Database: db_name Timeout: 10s TLS: true MaxConns: 32
Types ¶
Click to show internal directories.
Click to hide internal directories.