-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
37 lines (31 loc) · 828 Bytes
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package jsonfeed
import (
"bytes"
"encoding/json"
"fmt"
"io"
)
type FeedConstraint interface {
IsEmpty() bool
}
func FromBytes[F FeedConstraint](jsonBytes []byte) (feed *F, err error) {
err = json.Unmarshal(jsonBytes, &feed)
if err == nil && (feed == nil || (*feed).IsEmpty()) {
err = fmt.Errorf("unmarshalling ok, but Feed object is nil or empty, check the json for valid jsonfeed data")
}
return
}
func FromString[F FeedConstraint](jsonStr string) (feed *F, err error) {
jsonBytes := bytes.NewBufferString(jsonStr).Bytes()
return FromBytes[F](jsonBytes)
}
func FromReader[F FeedConstraint](reader io.Reader) (feed *F, err error) {
if reader == nil {
return nil, fmt.Errorf("reader was nil")
}
jsonBytes, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
return FromBytes[F](jsonBytes)
}