Skip to content

Commit

Permalink
added required env variables logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Asliddin Azizovich committed Aug 9, 2021
1 parent 354075c commit 7b63583
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
20 changes: 15 additions & 5 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goenv

import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
Expand All @@ -10,8 +11,9 @@ import (
)

type Config struct {
EnvTag string
DefaultValueTag string
EnvTag string
DefaultValueTag string
RequiredValueTag string
}

type ParserFunc func(value string) (interface{}, error)
Expand All @@ -21,12 +23,13 @@ var (
ErrNoStruct = errors.New("given parameter is not a struct")
// ErrNoPtr error when given parameter is not pointer
ErrNoPtr = errors.New("given parameter is not a pointer")

// DefaultTag tag for loading env key names from struct
DefaultTag = "env"

// Default value of env variable
DefaultValueTag = "default"
// Required env variable
DefaultRequiredTag = "required"

// Built-in parser functions
BuiltInParsers = map[reflect.Kind]ParserFunc{
Expand Down Expand Up @@ -121,8 +124,9 @@ func New(envFiles ...string) (Config, error) {
}

return Config{
EnvTag: DefaultTag,
DefaultValueTag: DefaultValueTag,
EnvTag: DefaultTag,
DefaultValueTag: DefaultValueTag,
RequiredValueTag: DefaultRequiredTag,
}, nil
}

Expand Down Expand Up @@ -155,6 +159,8 @@ func (e Config) Parse(s interface{}) error {

typeField := t.Field(i)
key, defaultValue := typeField.Tag.Get(e.EnvTag), typeField.Tag.Get(e.DefaultValueTag)
isRequired := typeField.Tag.Get(e.RequiredValueTag) == "true"

if key != "" {
value := e.getOrDefault(key, defaultValue)

Expand All @@ -165,6 +171,10 @@ func (e Config) Parse(s interface{}) error {
return err
}

if parsedValue == "" && isRequired {
return fmt.Errorf("%s required", key)
}

reflectValue.Field(i).Set(reflect.ValueOf(parsedValue))
}
}
Expand Down
1 change: 1 addition & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ func TestParse(t *testing.T) {
DBName string `env:"DB_NAME" default:"postgres"`
Port int64 `env:"PORT" default:"8080"`
FeePercent float32 `env:"FEE_PERCENT" default:"1"`
URL string `env:"URL" required:"true" default:"https://google.com"`
}{}

if err := env.Parse(&config); err != nil {
Expand Down

0 comments on commit 7b63583

Please sign in to comment.