-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathjson.go
More file actions
89 lines (79 loc) · 1.9 KB
/
Copy pathjson.go
File metadata and controls
89 lines (79 loc) · 1.9 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package api
import (
"io"
"reflect"
"github.com/Aize-Public/forego/ctx"
"github.com/Aize-Public/forego/enc"
)
// implementation for all the client/server request/responses using json
// Note(oha): the object is not goroutine safe, but it's not expected to be
type JSON struct {
h enc.Handler
j enc.JSON
Data enc.Map
UID enc.Node
}
var _ ClientRequest = &JSON{}
var _ ServerRequest = &JSON{}
var _ ServerResponse = &JSON{}
var _ ClientResponse = &JSON{}
func (this JSON) String() string {
j, _ := enc.MarshalJSON(ctx.TODO(), this)
return string(j)
}
func (this *JSON) ReadFrom(c ctx.C, r io.Reader) error {
data, err := io.ReadAll(r)
if err != nil {
return ctx.NewErrorf(c, "can't read api.JSON: %w", err)
}
if len(data) == 0 {
this.Data = enc.Map{}
return nil
}
n, err := this.j.Decode(c, data)
if err != nil {
return err
}
switch n := n.(type) {
case enc.Map:
this.Data = n
default:
return ctx.NewErrorf(c, "expected object, got %s", data)
}
return nil
}
func (this *JSON) Auth(c ctx.C, into reflect.Value, required bool) error {
if (this.UID == nil || this.UID == enc.Nil{}) {
if required {
return ctx.NewErrorf(c, "Auth required")
}
return nil
}
return this.h.Unmarshal(c, this.UID, into.Addr().Interface())
}
func (this *JSON) Marshal(c ctx.C, name string, from reflect.Value) error {
if this.Data == nil {
this.Data = enc.Map{}
}
n, err := this.h.Marshal(c, from.Interface())
if err != nil {
return ctx.NewErrorf(c, "can't Marshal %q: %w", name, err)
}
this.Data[name] = n
return nil
}
func (this *JSON) Unmarshal(c ctx.C, name string, into reflect.Value) error {
if this.Data == nil {
this.Data = enc.Map{}
}
n, ok := this.Data[name]
if !ok {
return nil
}
err := this.h.Unmarshal(c, n, into.Addr().Interface())
//err := json.Unmarshal(j, into.Addr().Interface())
if err != nil {
return ctx.NewErrorf(c, "can't Unmarshal %q: %w", name, err)
}
return nil
}