-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
71 lines (57 loc) · 1.64 KB
/
decode.go
File metadata and controls
71 lines (57 loc) · 1.64 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
package mason
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"github.com/tailbits/mason/model"
)
type decodeOptions struct{}
type DecodeOption func(options *decodeOptions) error
func DecodeRequest[T model.Entity](api *API, r *http.Request, opts ...DecodeOption) (ent T, err error) {
if ent.Name() == "NilEntity" {
return ent, nil
}
var options decodeOptions
for _, opt := range opts {
err := opt(&options)
if err != nil {
return ent, err
}
}
body, err := io.ReadAll(r.Body)
if err != nil {
return ent, fmt.Errorf("unable to read the body: %w", err)
}
// restore the body for the next handler in the chain
r.Body = io.NopCloser(io.Reader(bytes.NewBuffer(body)))
schema, err := api.DereferenceSchema(ent.Schema())
if err != nil {
return ent, fmt.Errorf("dereferenceSchema ent[%s]: %w", ent.Name(), err)
}
if err := model.Validate(schema, body); err != nil {
return ent, fmt.Errorf("model.Validate: %w", err)
}
// If the entity is a pointer, we need to create a new instance of the entity,
// or else "ent" will be a nil pointer.
switch {
case reflect.TypeOf(ent).Kind() == reflect.Ptr:
elemType := reflect.TypeOf(ent).Elem()
newEnt := reflect.New(elemType).Interface()
var ok bool
if ent, ok = newEnt.(T); !ok {
return ent, fmt.Errorf("type assertion failed for entity of type %T", newEnt)
}
if err := json.Unmarshal(body, ent); err != nil {
return ent, fmt.Errorf("unable to unmarshal the data: %w", err)
}
return ent, nil
default:
if err := json.Unmarshal(body, &ent); err != nil {
return ent, fmt.Errorf("unable to unmarshal the data: %w", err)
}
return ent, nil
}
}