Skip to content

Commit 988c2b5

Browse files
committed
relax types for Bind and Render funcs
This relaxes the Bind and Render to accept any type as a payload. If those types implement the Binder or Renderer interfaces, then the relevant method on the type is called. Sometimes the default Bind or Render behavior is sufficient, and I don't need any additional custom handling. Return early if payload value is nil. Signed-off-by: Will Norris <will@tailscale.com>
1 parent 14f1cb3 commit 988c2b5

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

render.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,31 @@ type Binder interface {
1515
Bind(r *http.Request) error
1616
}
1717

18-
// Bind decodes a request body and executes the Binder method of the
19-
// payload structure.
20-
func Bind(r *http.Request, v Binder) error {
18+
// Bind decodes a request body into a payload structure.
19+
// If v implements the Binder interface, its Binder method is called.
20+
func Bind(r *http.Request, v interface{}) error {
21+
if v == nil {
22+
return nil
23+
}
2124
if err := Decode(r, v); err != nil {
2225
return err
2326
}
24-
return binder(r, v)
27+
if b, ok := v.(Binder); ok {
28+
return binder(r, b)
29+
}
30+
return nil
2531
}
2632

2733
// Render renders a single payload and respond to the client request.
28-
func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {
29-
if err := renderer(w, r, v); err != nil {
30-
return err
34+
// If v implements the Renderer interface, its Render method is called.
35+
func Render(w http.ResponseWriter, r *http.Request, v interface{}) error {
36+
if v == nil {
37+
return nil
38+
}
39+
if rd, ok := v.(Renderer); ok {
40+
if err := renderer(w, r, rd); err != nil {
41+
return err
42+
}
3143
}
3244
Respond(w, r, v)
3345
return nil

0 commit comments

Comments
 (0)