mirror of
https://github.com/Luzifer/rconfig.git
synced 2024-11-09 00:10:07 +00:00
Update README with better examples
This commit is contained in:
parent
c27bd3a64b
commit
b838290304
1 changed files with 20 additions and 27 deletions
47
README.md
47
README.md
|
@ -29,34 +29,31 @@ go test -v -race -cover github.com/Luzifer/rconfig
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
As a first step define a struct holding your configuration:
|
A very simple usecase is to just configure a struct inside the vars section of your `main.go` and to parse the commandline flags from the `main()` function:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type config struct {
|
package main
|
||||||
Username string `default:"unknown" flag:"user" description:"Your name"`
|
|
||||||
Details struct {
|
|
||||||
Age int `default:"25" flag:"age" env:"age" description:"Your age"`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Next create an instance of that struct and let `rconfig` fill that config:
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/Luzifer/rconfig"
|
||||||
|
)
|
||||||
|
|
||||||
```go
|
var (
|
||||||
var cfg config
|
cfg = struct {
|
||||||
func init() {
|
Username string `default:"unknown" flag:"user" description:"Your name"`
|
||||||
cfg = config{}
|
Details struct {
|
||||||
rconfig.Parse(&cfg)
|
Age int `default:"25" flag:"age" env:"age" description:"Your age"`
|
||||||
}
|
}
|
||||||
```
|
}{}
|
||||||
|
)
|
||||||
|
|
||||||
You're ready to access your configuration:
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
func main() {
|
||||||
|
rconfig.Parse(&cfg)
|
||||||
|
|
||||||
fmt.Printf("Hello %s, happy birthday for your %dth birthday.",
|
fmt.Printf("Hello %s, happy birthday for your %dth birthday.",
|
||||||
cfg.Username,
|
cfg.Username,
|
||||||
cfg.Details.Age)
|
cfg.Details.Age)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -72,18 +69,14 @@ The order of the directives (lower number = higher precedence):
|
||||||
1. `default` tag in the struct
|
1. `default` tag in the struct
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type config struct {
|
var cfg = struct {
|
||||||
Username string `vardefault:"username" flag:"username" description:"Your username"`
|
Username string `vardefault:"username" flag:"username" description:"Your username"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var cfg = config{}
|
func main() {
|
||||||
|
|
||||||
func init() {
|
|
||||||
rconfig.SetVariableDefaults(rconfig.VarDefaultsFromYAMLFile("~/.myapp.yml"))
|
rconfig.SetVariableDefaults(rconfig.VarDefaultsFromYAMLFile("~/.myapp.yml"))
|
||||||
rconfig.Parse(&cfg)
|
rconfig.Parse(&cfg)
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
fmt.Printf("Username = %s", cfg.Username)
|
fmt.Printf("Username = %s", cfg.Username)
|
||||||
// Output: Username = luzifer
|
// Output: Username = luzifer
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue