responder

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2019 License: MIT Imports: 4 Imported by: 9

README

github.com/gobuffalo/x/responder

$ go get -u github.com/gobuffalo/x/responder

This packages allows you to easily write "responders" that trigger different functions based on the incoming request Content-Type header.

For example, if you have a UserList buffalo.Handler that you want to be able to respond differently to HTML or JSON you can write a couple of responder functions that handle those different requests.

func UserList(c buffalo.Context) error {
  // do some work
  return responder.Wants("html", func (c buffalo.Context) error {
    return c.Render(200, r.HTML("some/template.html"))
  }).Wants("json", func (c buffalo.Context) error {
    return c.Render(200, r.JSON(user))
  }).Respond(c)
}

// Alternate version
func UserList(c buffalo.Context) error {
  // do some work
  res :=  responder.Wants("html", func (c buffalo.Context) error {
    return c.Render(200, r.HTML("some/template.html"))
  })
  res.Wants("json", func (c buffalo.Context) error {
    return c.Render(200, r.JSON(user))
  })
  return res.Respond(c)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Responder

type Responder struct {
	// contains filtered or unexported fields
}

Responder holds the mappings of content-type to handler

func Wants

func Wants(ct string, h buffalo.Handler) Responder

Wants maps a content-type, or part of one ("json", "html", "form", etc...), to a buffalo.Handler to respond with when it gets that content-type, returns a Responder that can be used for further mappings.

func (Responder) Respond

func (r Responder) Respond(ctx buffalo.Context) error

Respond with a mapped buffalo.Handler, if one exists, returns an error if one does not.

func UserList(c buffalo.Context) error {
	// do some work
	return responder.Wants("html", func (c buffalo.Context) error {
		return c.Render(200, r.HTML("some/template.html")
	}).Wants("json", func (c buffalo.Context) error {
		return c.Render(200, r.JSON(user))
	}).Respond(c)
}

func (Responder) Wants

func (r Responder) Wants(ct string, h buffalo.Handler) Responder

Wants maps a content-type, or part of one ("json", "html", "form", etc...), to a buffalo.Handler to respond with when it gets that content-type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL