-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreactor.go
99 lines (79 loc) · 1.68 KB
/
reactor.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
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
90
91
92
93
94
95
96
97
98
99
package restify
import (
"net/http"
"github.com/phogolabs/inflate"
)
// Reactor works with http response and request
type Reactor struct {
decoder *Decoder
encoder *Encoder
validator *Validator
}
// NewReactor creates a new reactor
func NewReactor(w http.ResponseWriter, r *http.Request) *Reactor {
validator := NewValidator(r)
validator.skip = 2
reactor := &Reactor{
decoder: NewDecoder(r),
encoder: NewEncoder(w, r),
validator: validator,
}
return reactor
}
// Status sets the response status code
func (r *Reactor) Status(code int) {
r.encoder.Status(code)
}
// Bind binds the object
func (r *Reactor) Bind(obj interface{}) (err error) {
// decode the body
if err = r.decoder.Decode(obj); err != nil {
return err
}
// set defaults
if err == nil {
err = inflate.SetDefault(obj)
}
// validate
if err == nil {
err = r.validator.Validate(obj)
}
if err == nil {
// bind the input
err = r.binder(obj)
}
return err
}
// Render renders the response
func (r *Reactor) Render(obj interface{}) (err error) {
// handle error
if errx, ok := obj.(error); ok {
obj = r.log(r.error(errx))
}
if obj != nil {
// set defaults
if err = inflate.SetDefault(obj); err != nil {
return err
}
}
// encode the body
if err = r.encoder.Encode(obj); err != nil {
return err
}
if err == nil {
// render the output
if renderer, ok := obj.(Renderer); ok {
err = r.renderer(renderer)
}
}
return err
}
// RenderWith renders the response with code
func (r *Reactor) RenderWith(code int, obj interface{}) (err error) {
r.Status(code)
// handle error
if errx, ok := obj.(error); ok {
obj = r.error(errx).WithStatus(code)
}
return r.Render(obj)
}