Skip to content

Commit

Permalink
add example to inject env into stuct fields
Browse files Browse the repository at this point in the history
  • Loading branch information
shaj13 committed Nov 4, 2022
1 parent 5ef4075 commit b35a5fb
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ func init() {
env.Var(&intervalEnv, "delta_t", "comma-separated list of intervals to use between events")
}

type Config struct {
Host string
Port string
// ....
}

func init() {
cfg := new(Config)
// Tie the environ to the struct fields and
// set a usage messages.
env.StringVar(&cfg.Host, "host", "localhost", "App host name")
env.StringVar(&cfg.Port, "port", "443", "App port")
}

func main() {
os.Setenv("DELTA_T", "1s,2m,3h")

Expand Down
31 changes: 31 additions & 0 deletions example_struct_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package env_test

import (
"fmt"

"github.com/shaj13/env"
)

type Config struct {
Host string
Port string
// ....
}

func Example_struct() {
cfg := new(Config)

es := env.NewEnvSet("app", env.ExitOnError)
es.StringVar(&cfg.Host, "host", "localhost", "App host name")
es.StringVar(&cfg.Port, "port", "443", "App port")

es.Parse([]string{"APP_HOST=env.localhost"})
fmt.Printf(`%s:%s`, cfg.Host, cfg.Port)

// Output:
// env.localhost:443
}

0 comments on commit b35a5fb

Please sign in to comment.