/
format_crappy_json.go
52 lines (40 loc) · 1006 Bytes
/
format_crappy_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
package test_helper
import (
"encoding/json"
"errors"
"github.com/hjwalt/runway/format"
reflect "github.com/hjwalt/runway/reflect"
)
type CrappyJsonFormat[T CrappyShouldError] struct{}
type CrappyShouldError interface {
ShouldError() bool
}
func (helper CrappyJsonFormat[T]) Default() T {
return reflect.Construct[T]()
}
func (helper CrappyJsonFormat[T]) Marshal(value T) ([]byte, error) {
if reflect.IsNil(value) {
return nil, nil
}
if value.ShouldError() {
return make([]byte, 0), errors.New("crappy")
}
return json.Marshal(value)
}
func (helper CrappyJsonFormat[T]) Unmarshal(value []byte) (T, error) {
if len(value) == 0 {
return helper.Default(), nil
}
jsonMessage := helper.Default()
err := json.Unmarshal(value, jsonMessage)
if err != nil {
return jsonMessage, err
}
if jsonMessage.ShouldError() {
return jsonMessage, errors.New("crappy")
}
return jsonMessage, nil
}
func CrappyJson[T CrappyShouldError]() format.Format[T] {
return CrappyJsonFormat[T]{}
}