-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
57 lines (40 loc) · 1.1 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
package json
import (
"context"
"encoding/json"
"log/slog"
)
// JsonUnmarshaller is a generic task to unmarshall JSONs.
type JsonUnmarshaller[I []byte, O any] struct {
logger *slog.Logger
}
func NewJsonUnmarshaller[I []byte, O any](logger *slog.Logger) *JsonUnmarshaller[I, O] {
u := new(JsonUnmarshaller[I, O])
u.logger = logger
return u
}
func (u *JsonUnmarshaller[I, O]) Run(_ context.Context, input []byte, meta map[string]interface{}, _ string) (O, error) {
var target O
err := json.Unmarshal(input, &target)
if err != nil {
var nullTarget O
return nullTarget, err
}
return target, nil
}
// JsonMarshaller is a generic task which marshal any given struct into JSON.
type JsonMarshaller[I any, O []byte] struct {
logger *slog.Logger
}
func NewJsonMarshaller[I any, O []byte](logger *slog.Logger) *JsonMarshaller[I, O] {
u := new(JsonMarshaller[I, O])
u.logger = logger
return u
}
func (u *JsonMarshaller[I, O]) Run(_ context.Context, input I, meta map[string]interface{}, _ string) (O, error) {
bytes, err := json.Marshal(input)
if err != nil {
return nil, err
}
return bytes, nil
}