Improve this page

Action Controller

In this chapter, you'll learn how action controllers work; and how you can generate them using the built-in generators.

What is a Controller?

Controllers are the C part of the MVC pattern. They handle the logic given the router decision, and produce an appropriate response.

For instance, if you request the / path of this website, the handler responsible of the home page will produce you the HTML home page as you see it. If you're building a REST API, the controller will fetch or save some data, then ask (politely) the render engine to produce the appropriate response.

In Buffalo case, we commonly call controllers "actions".

Define an Action

Buffalo's actions (or controllers) are buffalo#Handler functions:

func Home(c buffalo.Context) error {
	return c.Render(200, r.HTML("home.html"))
}

In this example, we defined a "Home" action, and asked the rendering engine to produce an HTML page using the "home.html" template, and to reply with an HTTP 200 code.

Each action takes a buffalo.Context as parameter: see Context to learn more about all you can do with it.

Generating Actions

Since writing actions boilerplate is quite redundant, Buffalo provides you a generator to help you.

$ buffalo g action --help

Generates new action(s)

Usage:
  buffalo generate action [name] [actionName...] [flags]

Aliases:
  action, a, actions
$ buffalo g a users show index create

--> templates/users/show.html
--> templates/users/index.html
--> templates/users/create.html
--> actions/users.go
--> actions/users_test.go
--> goimports -w .

In some cases you will need to generate an action with an HTTP method different than GET, for that case you can use the --method flag, like in the following example:

$ buffalo g actions users message --method POST

In some other scenarios you will need to generate an action without generating an HTML template. To skip the generation of the HTML template for creating an action you can pass the --skip-template flag to the generator, i.e:

$ buffalo g actions users update --skip-template

Destroying Actions

You can remove files generated by this generator by running:

$ buffalo destroy action users

Or in short form:

$ buffalo d a users

Next Steps

  • Resources - Define CRUD-like action bundles.
  • Context - Learn more about Buffalo Context.