-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
json_to_chan.go
60 lines (47 loc) · 964 Bytes
/
json_to_chan.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) 2021-2024 Onur Cinar.
// The source code is provided under GNU AGPLv3 License.
// https://github.com/cinar/indicator
package helper
import (
"encoding/json"
"io"
"log"
)
// JSONToChan reads values from the specified reader in JSON format into a channel of values.
//
// Example:
func JSONToChan[T any](r io.Reader) <-chan T {
c := make(chan T)
go func() {
defer close(c)
decoder := json.NewDecoder(r)
token, err := decoder.Token()
if err != nil {
log.Print(err)
return
}
if token != json.Delim('[') {
log.Printf("expecting start of array got %v", token)
return
}
for decoder.More() {
var value T
err = decoder.Decode(&value)
if err != nil {
log.Print(err)
return
}
c <- value
}
token, err = decoder.Token()
if err != nil {
log.Print(err)
return
}
if token != json.Delim(']') {
log.Printf("expecting end of array got %v", token)
return
}
}()
return c
}