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
161 changes: 89 additions & 72 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
defaults
========
# defaults

[![CircleCI](https://circleci.com/gh/creasty/defaults/tree/master.svg?style=svg)](https://circleci.com/gh/creasty/defaults/tree/master)
[![codecov](https://codecov.io/gh/creasty/defaults/branch/master/graph/badge.svg)](https://codecov.io/gh/creasty/defaults)
Expand All @@ -24,10 +23,9 @@ Initialize structs with default values
- Recursively initializes fields in a struct
- Dynamically sets default values by [`defaults.Setter`](./setter.go) interface
- Preserves non-initial values from being reset with a default value
- Set default values for all addressable structs


Usage
-----
## 1. Usage

```go
package main
Expand Down Expand Up @@ -58,6 +56,9 @@ type Sample struct {
MapOfPtrStruct map[string]*OtherStruct `default:"{\"Key3\": {\"Foo\":123}}"`
MapOfStructWithTag map[string]OtherStruct `default:"{\"Key4\": {\"Foo\":123}}"`

MapOfStructWithOutTag map[string]OtherStruct
MapOfSliceWithOutTag map[string][]OtherStruct

Struct OtherStruct `default:"{\"Foo\": 123}"`
StructPtr *OtherStruct `default:"{\"Foo\": 123}"`

Expand All @@ -79,7 +80,16 @@ func (s *OtherStruct) SetDefaults() {
}

func main() {
obj := &Sample{}
obj := &Sample{
MapOfStructWithOutTag: map[string]OtherStruct{
"hello": {},
},
MapOfSliceWithOutTag: map[string][]OtherStruct{
"hello": {
{},
},
},
}
if err := defaults.Set(obj); err != nil {
panic(err)
}
Expand All @@ -89,72 +99,79 @@ func main() {
panic(err)
}
fmt.Println(string(out))
```

// Output:
// {
// "Name": "John Smith",
// "Age": 27,
// "Gender": "m",
// "Working": true,
// "SliceInt": [
// 1,
// 2,
// 3
// ],
// "SlicePtr": [
// 1,
// 2,
// 3
// ],
// "SliceString": [
// "a",
// "b"
// ],
// "MapNull": {},
// "Map": {
// "key1": 123
// },
// "MapOfStruct": {
// "Key2": {
// "Hello": "world",
// "Foo": 123,
// "Random": 5577006791947779410
// }
// },
// "MapOfPtrStruct": {
// "Key3": {
// "Hello": "world",
// "Foo": 123,
// "Random": 8674665223082153551
// }
// },
// "MapOfStructWithTag": {
// "Key4": {
// "Hello": "world",
// "Foo": 123,
// "Random": 6129484611666145821
// }
// },
// "Struct": {
// "Hello": "world",
// "Foo": 123,
// "Random": 4037200794235010051
// },
// "StructPtr": {
// "Hello": "world",
// "Foo": 123,
// "Random": 3916589616287113937
// },
// "NoTag": {
// "Hello": "world",
// "Foo": 0,
// "Random": 6334824724549167320
// },
// "NoOption": {
// "Hello": "",
// "Foo": 0,
// "Random": 0
// }
// }
output

```json
{
"Name": "John Smith",
"Age": 27,
"Gender": "m",
"Working": true,
"SliceInt": [1, 2, 3],
"SlicePtr": [1, 2, 3],
"SliceString": ["a", "b"],
"MapNull": {},
"Map": {
"key1": 123
},
"MapOfStruct": {
"Key2": {
"Hello": "world",
"Foo": 123,
"Random": 6012378114984103869
}
},
"MapOfPtrStruct": {
"Key3": {
"Hello": "world",
"Foo": 123,
"Random": 2848306665585403127
}
},
"MapOfStructWithTag": {
"Key4": {
"Hello": "world",
"Foo": 123,
"Random": 7421038243474730390
}
},
"MapOfStructWithOutTag": {
"hello": {
"Hello": "world",
"Foo": 0,
"Random": 6214942057906930174
}
},
"MapOfSliceWithOutTag": {
"hello": [
{
"Hello": "world",
"Foo": 0,
"Random": 5317591004601161060
}
]
},
"Struct": {
"Hello": "world",
"Foo": 123,
"Random": 3365636741323893358
},
"StructPtr": {
"Hello": "world",
"Foo": 123,
"Random": 4271644362335896782
},
"NoTag": {
"Hello": "world",
"Foo": 0,
"Random": 8353712922077708401
},
"NoOption": {
"Hello": "",
"Foo": 0,
"Random": 0
}
}
```
32 changes: 20 additions & 12 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,23 +175,31 @@
}
case reflect.Map:
for _, e := range field.MapKeys() {
var v = field.MapIndex(e)
v := field.MapIndex(e)

switch v.Kind() {
case reflect.Ptr:
switch v.Elem().Kind() {
case reflect.Struct, reflect.Slice, reflect.Map:
if err := setField(v.Elem(), ""); err != nil {
return err
}
originalIsPtr := v.Kind() == reflect.Ptr
if originalIsPtr {
if v.IsNil() {
continue

Check warning on line 183 in defaults.go

View check run for this annotation

Codecov / codecov/patch

defaults.go#L183

Added line #L183 was not covered by tests
}
v = v.Elem()
}

switch v.Kind() {
case reflect.Struct, reflect.Slice, reflect.Map:
ref := reflect.New(v.Type())
ref.Elem().Set(v)
if err := setField(ref.Elem(), ""); err != nil {
if !v.CanAddr() {
copyValue := reflect.New(v.Type())
copyValue.Elem().Set(v)
v = copyValue.Elem()
}

if err := setField(v, ""); err != nil {
return err
}
field.SetMapIndex(e, ref.Elem().Convert(v.Type()))

if !originalIsPtr {
field.SetMapIndex(e, v)
}
}
}
}
Expand Down
23 changes: 21 additions & 2 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ func (j *JSONOnlyType) UnmarshalJSON(b []byte) error {
}

func TestMustSet(t *testing.T) {

t.Run("right way", func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
Expand Down Expand Up @@ -226,7 +225,6 @@ func TestMustSet(t *testing.T) {
}
MustSet(sample)
})

}

func TestInit(t *testing.T) {
Expand Down Expand Up @@ -769,3 +767,24 @@ func TestDefaultsSetter(t *testing.T) {
t.Errorf("expected 1 for MainInt, got %d", main.MainInt)
}
}

type ParentWithMapOfSliceOfChild struct {
Children map[string][]Child
}

func TestMapOfSliceOfStruct(t *testing.T) {
p := &ParentWithMapOfSliceOfChild{
Children: map[string][]Child{
"group1": {
{Name: "Jim"},
},
},
}
Set(p)
if p.Children["group1"][0].Age != 20 {
t.Errorf("expected age to be 20, got %d", p.Children["group1"][0].Age)
}
if p.Children["group1"][0].Name != "Jim" {
t.Errorf("expected name to be Jim, got %s", p.Children["group1"][0].Name)
}
}
81 changes: 13 additions & 68 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ type Sample struct {
MapOfPtrStruct map[string]*OtherStruct `default:"{\"Key3\": {\"Foo\":123}}"`
MapOfStructWithTag map[string]OtherStruct `default:"{\"Key4\": {\"Foo\":123}}"`

MapOfStructWithOutTag map[string]OtherStruct
MapOfSliceWithOutTag map[string][]OtherStruct

Struct OtherStruct `default:"{\"Foo\": 123}"`
StructPtr *OtherStruct `default:"{\"Foo\": 123}"`

Expand All @@ -47,7 +50,16 @@ func (s *OtherStruct) SetDefaults() {
}

func main() {
obj := &Sample{}
obj := &Sample{
MapOfStructWithOutTag: map[string]OtherStruct{
"hello": {},
},
MapOfSliceWithOutTag: map[string][]OtherStruct{
"hello": {
{},
},
},
}
if err := defaults.Set(obj); err != nil {
panic(err)
}
Expand All @@ -57,71 +69,4 @@ func main() {
panic(err)
}
fmt.Println(string(out))

// Output:
// {
// "Name": "John Smith",
// "Age": 27,
// "Gender": "m",
// "Working": true,
// "SliceInt": [
// 1,
// 2,
// 3
// ],
// "SlicePtr": [
// 1,
// 2,
// 3
// ],
// "SliceString": [
// "a",
// "b"
// ],
// "MapNull": {},
// "Map": {
// "key1": 123
// },
// "MapOfStruct": {
// "Key2": {
// "Hello": "world",
// "Foo": 123,
// "Random": 5577006791947779410
// }
// },
// "MapOfPtrStruct": {
// "Key3": {
// "Hello": "world",
// "Foo": 123,
// "Random": 8674665223082153551
// }
// },
// "MapOfStructWithTag": {
// "Key4": {
// "Hello": "world",
// "Foo": 123,
// "Random": 6129484611666145821
// }
// },
// "Struct": {
// "Hello": "world",
// "Foo": 123,
// "Random": 4037200794235010051
// },
// "StructPtr": {
// "Hello": "world",
// "Foo": 123,
// "Random": 3916589616287113937
// },
// "NoTag": {
// "Hello": "world",
// "Foo": 0,
// "Random": 6334824724549167320
// },
// "NoOption": {
// "Hello": "",
// "Foo": 0,
// "Random": 0
// }
// }
}
Loading