Skip to content

Commit

Permalink
Merge pull request #1 from cryptix/multiple-loads
Browse files Browse the repository at this point in the history
Merge PR that allows calling Load multiple times.
  • Loading branch information
keks authored Oct 6, 2019
2 parents 3af502d + a51e5e7 commit 43c1240
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/keks/persist

require github.com/pkg/errors v0.8.1
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
6 changes: 5 additions & 1 deletion persist.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ func Save(f *os.File, v interface{}) error {
// Use os.IsNotExist() to see if the returned error is due
// to the file being missing.
func Load(f *os.File, v interface{}) error {
err := json.NewDecoder(f).Decode(v)
_, err := f.Seek(0, 0)
if err != nil {
return errors.Wrap(err, "error reetting reader")
}
err = json.NewDecoder(f).Decode(v)
return errors.Wrap(err, "error decoding value")
}
10 changes: 10 additions & 0 deletions persist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,14 @@ func TestPersist(t *testing.T) {
is.Equal(o.Name, o2.Name)
is.Equal(o.Number, o2.Number)
is.True(o.When.Equal(o2.When))

// load it, twice
o2.Name = ""
o2.Number = 0
err = persist.Load(f, &o2)
is.NoErr(err)

is.Equal(o.Name, o2.Name)
is.Equal(o.Number, o2.Number)
is.True(o.When.Equal(o2.When))
}

0 comments on commit 43c1240

Please sign in to comment.