-
Notifications
You must be signed in to change notification settings - Fork 20
/
json.go
58 lines (51 loc) · 1.45 KB
/
json.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
package encoding
import (
"encoding/json"
"github.com/cloudflare/golog/logger"
"github.com/cloudflare/go-stream/stream"
"github.com/cloudflare/go-stream/stream/mapper"
"github.com/cloudflare/go-stream/util/slog"
//"reflect"
)
/* Example Decoder Usage
intDecGenFn := func () interface{} {
decoder := encoding.JsonGeneralDecoder()
return func(in []byte, closenotifier chan<- bool) []int {
var i int
decoder(in, &i)
return []int{i}
}
}
intDecOp := encoding.NewJsonDecodeRop(intDecGenFn)
*/
func JsonGeneralDecoder() func([]byte, interface{}) {
fn := func(input []byte, to_populate interface{}) {
err := json.Unmarshal(input, to_populate)
if err != nil {
slog.Logf(logger.Levels.Error, "Error unmarshaling json: %v %v\n", err.Error(), string(input))
}
}
return fn
}
func JsonGeneralEncoder() func(interface{}) ([]byte, error) {
fn := func(input interface{}) ([]byte, error) {
return json.Marshal(input)
}
return fn
}
func NewJsonDecodeRop(gen interface{}) stream.Operator { //if outch is chan X, gen should be func() (func([]byte, chan<-bool) []X)
return mapper.NewOpFactory(gen, "JsonDecodeRop")
}
func NewJsonEncodeRop() stream.Operator {
generator := func() interface{} {
fn := func(in interface{}) [][]byte {
out, err := json.Marshal(in)
if err != nil {
slog.Logf(logger.Levels.Error, "Error marshaling json %v\t%+v", err, in)
}
return [][]byte{out}
}
return fn
}
return mapper.NewOpFactory(generator, "NewJsonEncodeRop")
}