Skip to content

Commit

Permalink
add check to ignore nil decodable if value is empty (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajatprabha authored Jun 24, 2024
1 parent 42ae8c8 commit 7b8c808
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions xload/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ func doProcess(ctx context.Context, obj any, tagKey string, loader Loader) error
return &ErrRequired{key: meta.key}
}

if val == "" && isNilStructPtr {
continue
}

if ok, err := decode(fVal, val); ok {
if err != nil {
return &ErrDecode{
Expand Down
24 changes: 24 additions & 0 deletions xload/load_struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import (
"context"
"encoding/json"
"errors"
"net"
"reflect"
"testing"
"time"

"github.com/gotidy/ptr"
"github.com/stretchr/testify/assert"

xloadtype "github.com/gojekfarm/xtools/xload/type"
)

type House struct {
Expand Down Expand Up @@ -399,3 +402,24 @@ func TestLoad_JSON(t *testing.T) {

runTestcases(t, testcases)
}

func TestLoad_keyCollisions(t *testing.T) {
t.Run("MissingNestedNillableKeyRegression", func(t *testing.T) {
type ServerConfig struct {
HTTP *xloadtype.Listener `env:"ADDRESS"`
}
type Config struct {
Server ServerConfig `env:",prefix=SERVER_"`
}

cfg1 := new(Config)
assert.NoError(t, Load(context.TODO(), cfg1))
assert.Nil(t, cfg1.Server.HTTP)

cfg2 := new(Config)
assert.NoError(t, Load(context.TODO(), cfg2, MapLoader{"SERVER_ADDRESS": "127.0.0.1:80"}))
assert.NotNil(t, cfg2.Server.HTTP)
assert.Equal(t, net.IPv4(127, 0, 0, 1), cfg2.Server.HTTP.IP)
assert.Equal(t, 80, cfg2.Server.HTTP.Port)
})
}

0 comments on commit 7b8c808

Please sign in to comment.