Skip to content

Commit

Permalink
relax types for Bind and Render funcs
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
willnorris committed Mar 8, 2024
1 parent 14f1cb3 commit 988c2b5
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions render.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,31 @@ type Binder interface {
Bind(r *http.Request) error
}

// Bind decodes a request body and executes the Binder method of the
// payload structure.
func Bind(r *http.Request, v Binder) error {
// Bind decodes a request body into a payload structure.
// If v implements the Binder interface, its Binder method is called.
func Bind(r *http.Request, v interface{}) error {
if v == nil {
return nil
}
if err := Decode(r, v); err != nil {
return err
}
return binder(r, v)
if b, ok := v.(Binder); ok {
return binder(r, b)
}
return nil
}

// Render renders a single payload and respond to the client request.
func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {
if err := renderer(w, r, v); err != nil {
return err
// If v implements the Renderer interface, its Render method is called.
func Render(w http.ResponseWriter, r *http.Request, v interface{}) error {
if v == nil {
return nil
}
if rd, ok := v.(Renderer); ok {
if err := renderer(w, r, rd); err != nil {
return err
}
}
Respond(w, r, v)
return nil
Expand Down

0 comments on commit 988c2b5

Please sign in to comment.