Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,13 +381,21 @@ func (s *Section) mapToSlice(secName string, val reflect.Value, isStrict bool) (
func (s *Section) mapTo(v interface{}, isStrict bool) error {
typ := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if typ == nil || !val.IsValid() {
return errors.New("nil pointer to a struct")
}
if typ.Kind() == reflect.Pointer {
typ = typ.Elem()
val = val.Elem()
} else {
return errors.New("not a pointer to a struct")
}

// MapTo(&cfg) where cfg is a nil *T used to panic in mapToField (#369).
if !val.IsValid() || (val.Kind() == reflect.Pointer && val.IsNil()) {
return errors.New("nil pointer to a struct")
}

if typ.Kind() == reflect.Slice {
newField, err := s.mapToSlice(s.name, val, isStrict)
if err != nil {
Expand Down
14 changes: 14 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -910,3 +910,17 @@ Title = Consultant Engineer
)
})
}

func TestMapToNilStructPointer(t *testing.T) {
t.Run("nil pointer to struct", func(t *testing.T) {
type Config struct {
User string `ini:"user"`
Pass string `ini:"pass"`
}
var cfg *Config
f, err := Load([]byte("user = alice\npass = secret\n"))
require.NoError(t, err)
err = f.MapTo(&cfg)
assert.EqualError(t, err, "nil pointer to a struct")
})
}