Skip to content

Commit

Permalink
Merge pull request #74 from mbenson/loadReader
Browse files Browse the repository at this point in the history
Load from io.Reader
  • Loading branch information
magiconair authored Dec 7, 2024
2 parents 52d9efe + 1d2f669 commit ed5b6ef
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions load.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ func (l *Loader) LoadBytes(buf []byte) (*Properties, error) {
return l.loadBytes(buf, l.Encoding)
}

// LoadReader reads an io.Reader into a Properties struct.
func (l *Loader) LoadReader(r io.Reader) (*Properties, error) {
if buf, err := io.ReadAll(r); err != nil {
return nil, err
} else {
return l.loadBytes(buf, l.Encoding)
}
}

// LoadAll reads the content of multiple URLs or files in the given order into
// a Properties struct. If IgnoreMissing is true then a 404 status code or
// missing file will not be reported as error. Encoding sets the encoding for
Expand Down Expand Up @@ -185,6 +194,12 @@ func LoadFile(filename string, enc Encoding) (*Properties, error) {
return l.LoadAll([]string{filename})
}

// LoadReader reads an io.Reader into a Properties struct.
func LoadReader(r io.Reader, enc Encoding) (*Properties, error) {
l := &Loader{Encoding: enc}
return l.LoadReader(r)
}

// LoadFiles reads multiple files in the given order into
// a Properties struct. If 'ignoreMissing' is true then
// non-existent files will not be reported as error.
Expand Down Expand Up @@ -224,6 +239,12 @@ func MustLoadString(s string) *Properties {
return must(LoadString(s))
}

// MustLoadSReader reads an io.Reader into a Properties struct and
// panics on error.
func MustLoadReader(r io.Reader, enc Encoding) *Properties {
return must(LoadReader(r, enc))
}

// MustLoadFile reads a file into a Properties struct and
// panics on error.
func MustLoadFile(filename string, enc Encoding) *Properties {
Expand Down
15 changes: 15 additions & 0 deletions load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,21 @@ func TestLoadAll(t *testing.T) {
assertKeyValues(t, "", p, "key", "value4", "key2", "value2")
}

func TestLoadReader(t *testing.T) {
tf := make(tempFiles, 0)
defer tf.removeAll()

filename := tf.makeFile("key=value")
r, err := os.Open(filename)
if err != nil {
t.Fatal(err)
}
p := MustLoadReader(r, ISO_8859_1)

assert.Equal(t, p.Len(), 1)
assertKeyValues(t, "", p, "key", "value")
}

type tempFiles []string

func (tf *tempFiles) removeAll() {
Expand Down

0 comments on commit ed5b6ef

Please sign in to comment.