-
Notifications
You must be signed in to change notification settings - Fork 5
/
body.go
55 lines (47 loc) · 1.19 KB
/
body.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
package azugo
import (
"encoding/xml"
"io"
"github.com/goccy/go-json"
)
// BodyCtx represents the request body.
type BodyCtx struct {
noCopy noCopy //nolint:unused,structcheck
app *App
ctx *Context
}
// Bytes returns the request body as raw bytes.
func (b *BodyCtx) Bytes() []byte {
return b.ctx.Request().Body()
}
// Copy copies the request raw body to the provided writer.
func (b *BodyCtx) WriteTo(w io.Writer) error {
return b.ctx.context.Request.BodyWriteTo(w)
}
// JSON unmarshals the request body into provided structure.
// Optionally calls Validate method of the structure if it
// implements validation.Validator interface.
func (b *BodyCtx) JSON(v any) error {
buf := b.Bytes()
if len(buf) == 0 {
return ErrParamRequired{"body"}
}
if err := json.Unmarshal(buf, v); err != nil {
return ErrParamInvalid{"body", "json", err}
}
if v, ok := v.(Validator); ok {
return v.Validate(b.ctx)
}
return nil
}
// XML unmarshals the request body into provided structure.
func (b *BodyCtx) XML(v any) error {
buf := b.Bytes()
if len(buf) == 0 {
return ErrParamRequired{"body"}
}
if err := xml.Unmarshal(buf, v); err != nil {
return ErrParamInvalid{"body", "xml", err}
}
return nil
}