# Resources, controllers and routing

Source: https://bogie-go.com/docs/controllers.html

## A whole resource

```
bogie g scaffold post title:string body:text
```

This writes the model (everything [Models and migrations](https://bogie-go.com/docs/models.html) covers), the wire shapes in `app/views/posts.go`, and `app/controllers/posts_controller.go` with five real handlers over the store, registered. There is no HTML and no service layer.

```
      create  db/migrate/20261028094504_create_posts.sql
      create  db/queries/posts.sql
      create  app/models/post.go
      create  app/models/post_test.go
      create  db/adapter/posts.go
      create  db/adapter/posts_test.go
      create  test/factories/posts.go
      create  app/views/posts.go
      create  app/controllers/posts_controller.go
      create  app/controllers/posts_controller_test.go
      insert  app/controllers/application.go: Posts *PostsController
      insert  app/application.go: server.Posts = controllers.NewPostsController(store, log)
      insert  app/controllers/routes.go: s.Posts.SetupRoutes(&r.RouterGroup)
         run  sqlc generate
```

The model is named in the singular and the views and controller in the plural: `post`, but `PostsController` and `posts.go`. Run the same command again and every file and line is reported `identical`; a file you have since edited is reported `conflict` and nothing is written until you pass `--force`.

### The store interface

Declared beside the controller that uses it (rule 2), holding only the methods its actions call:

```
type postsStore interface {
	CreatePost(ctx context.Context, p models.Post) (models.Post, error)
	GetPost(ctx context.Context, id string) (models.Post, error)
	ListPosts(ctx context.Context, limit int32) ([]models.Post, error)
	UpdatePost(ctx context.Context, p models.Post) (models.Post, error)
	DeletePost(ctx context.Context, id string) error
}
```

`*adapter.Store` satisfies it without either package knowing about the other, and the interface lists exactly what the controller uses.

### SetupRoutes and one action

```
func (ctl *PostsController) SetupRoutes(router *gin.RouterGroup) {
	posts := router.Group("/posts")
	posts.GET("", ctl.Index)
	posts.POST("", ctl.Create)
	posts.GET("/:id", ctl.Show)
	posts.PATCH("/:id", ctl.Update)
	posts.DELETE("/:id", ctl.Destroy)
}

func (ctl *PostsController) Show(c *gin.Context) {
	p, err := ctl.Store.GetPost(c.Request.Context(), c.Param("id"))
	if err != nil {
		ctl.fail(c, err)
		return
	}
	c.JSON(http.StatusOK, postView(p))
}
```

A handler converts HTTP into model values, calls one store method, and converts the result back with `postView`. `*gin.Context` never travels below `app/controllers` (rule 5): nothing below this file ever sees `c`.

### fail: where error mapping lives

```
func (ctl *PostsController) fail(c *gin.Context, err error) {
	switch {
	case errors.Is(err, models.ErrNotFound):
		c.JSON(http.StatusNotFound, views.ErrorMessage("no such post"))
	case errors.Is(err, models.ErrInvalid):
		c.JSON(http.StatusUnprocessableEntity, views.Error(err))
	default:
		ctl.Log.ErrorContext(c.Request.Context(), "posts: request failed",
			"path", c.FullPath(), "err", err, "request_id", c.GetString("request_id"))
		c.JSON(http.StatusInternalServerError, views.ErrorMessage("internal error"))
	}
}
```

`models.ErrNotFound` is 404, `models.ErrInvalid` is 422 (validation runs in the store, on save), and anything else is logged with its request id and answered 500 without leaking its text. The request specs check the 404 and the 400 for a malformed body through the real app and the test database.

Try it: each call below fails on purpose and shows the real response. The app is the one from getting started with `bogie g scaffold post title:string body:text`, and a `Validate` that requires a title, as getting started shows for products. The `X-Request-Id`, `Date` and `Content-Length` headers are left out here, and the request id differs on every call.

**HTTP/1.1 404 Not Found** is a post that does not exist; `/posts/abc` gives the same 404 with `no such post`.

```
$ curl -i localhost:8080/posts/999
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8

{"status":"error","error":"no such post"}
```

PATCH and DELETE on `/posts/999` answer the same 404 with the same body.

**HTTP/1.1 422 Unprocessable Entity** is a post the model refuses to save, here an empty title (`invalid: title is required`):

```
$ curl -i -X POST localhost:8080/posts -H "Content-Type: application/json" -d '{"title":"","body":"hello"}'
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json; charset=utf-8

{"status":"error","error":"invalid: title is required"}
```

A PATCH with an empty title gives the same 422.

**HTTP/1.1 400 Bad Request** is a body that is not JSON, here one cut short (`unexpected EOF`); a POST with no body at all gives `EOF`.

```
$ curl -i -X POST localhost:8080/posts -H "Content-Type: application/json" -d '{"title":'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"status":"error","error":"unexpected EOF"}
```

**HTTP/1.1 404 Not Found** for a path with no route at all is not JSON but the page in `public/404.html`, whose title says `404 Not Found` and whose heading says `Off the map`:

```
$ curl -i localhost:8080/nope
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=utf-8

...
    <title>404 Not Found</title>
...
      <h1>Off the map</h1>
...
```

Done with a scaffold: `bogie d scaffold post` removes all of it, registration included. When a resource outgrows CRUD, [a service](https://bogie-go.com/docs/services.html) gives the logic a home that knows nothing about HTTP.

### Only some actions, or only the controller

`--only` writes just the actions you list, with their routes, store methods, views and request specs. The model half is always written whole:

```
bogie g scaffold category name:string:uniq --only index,show
```

That mounts `GET /categories` and `GET /categories/:id` and nothing else. To put the HTTP half over a model that already exists, in a namespace, use `scaffold_controller`. It reads the attributes back from `app/models` (so it takes none), writes views of its own, flat and prefixed like a model (`app/views/admin_categories.go`, `AdminCategoryResponse`; before v0.6.2 it shared the public views), and takes `--only` too:

```
bogie g scaffold_controller admin/categories
```

```
      create  app/controllers/admin_controllers/server.go
      create  app/controllers/admin_controllers/routes.go
      create  app/controllers/admin_controllers/admin_controllers_suite_test.go
      create  app/views/admin_categories.go
      create  app/controllers/admin_controllers/categories_controller.go
      create  app/controllers/admin_controllers/categories_controller_test.go
      insert  app/controllers/application.go: Admin *admin_controllers.Server
      insert  app/application.go: server.Admin = admin_controllers.NewServer(log)
      insert  app/controllers/routes.go: s.Admin.SetupRoutes(&r.RouterGroup)
      insert  app/controllers/admin_controllers/server.go: Categories *CategoriesController
      insert  app/application.go: server.Admin.Categories = admin_controllers.NewCategoriesController(store, log)
      insert  app/controllers/admin_controllers/routes.go: s.Categories.SetupRoutes(admin)
```

The model is the last segment of the name, never namespaced. `bogie g scaffold admin/page title`, by contrast, is a model of its own in a namespace: the model is `admin_page` (table `admin_pages`, `app/models/admin_page.go`) and its `PagesController` answers at `/admin/pages`. `bogie d scaffold_controller admin/categories` removes the controller and its spec, and the emptied namespace package.

A scaffold needs a name. `bogie g scaffold` alone prints the generator usage and ends with **bogie: generate scaffold: NAME is required**. Run it again with a name and attributes: `bogie g scaffold post title:string body:text`.

## A controller by hand

```
bogie g controller comments index show create
```

```
      create  app/controllers/comments_controller.go
      create  app/controllers/comments_controller_test.go
      insert  app/controllers/application.go: Comments *CommentsController
      insert  app/application.go: server.Comments = controllers.NewCommentsController(log)
      insert  app/controllers/routes.go: s.Comments.SetupRoutes(&r.RouterGroup)
```

One controller is one Go file: a `CommentsController` type holding its dependencies, `SetupRoutes`, and one method per action, with a test beside it. The actions are stubs answering 501 until filled in:

```
func (ctl *CommentsController) Create(c *gin.Context) {
	c.JSON(http.StatusNotImplemented, views.ErrorMessage("comments#create is not implemented yet"))
}
```

`index`, `show`, `create`, `update` and `destroy` get their resourceful routes (`GET /comments`, `GET /comments/:id`, and so on). Any other action name is a plain `GET` under that name: `bogie g controller comments search` mounts `GET /comments/search`. `new` and `edit` render forms and are refused outright:

```
bogie: generate controller: new renders a form; this is an API-only service, so there is no new action
```

Name a resource in the plural: the name is used as typed, so `bogie g controller post show` answers at `/post/:id`, not `/posts/:id`, and says so:

```
        note  A resource is named in the plural: posts would answer at /posts; post answers at /post
```

## The three markers

Go has no autoload: a controller exists only once it is constructed and mounted. That is three one-line insertions, each above a marker comment, and the generator makes all three, idempotently:

1. `app/controllers/application.go`, above `// bogie:controllers`: a named field, `Comments *CommentsController`.
2. `app/application.go`, above `// bogie:wire`: its construction, `server.Comments = controllers.NewCommentsController(log)`.
3. `app/controllers/routes.go`, above `// bogie:routes`: its mount, `s.Comments.SetupRoutes(&r.RouterGroup)`.

Run the same command again and every file and line is reported `identical`. `--pretend` reports what would be written without touching anything; a file that differs from what the generator would write is reported `conflict`, and only `--force` overwrites it. A marker missing from a file is a named error with no partial write; the generator never guesses. `bogie d controller comments` removes the file and all three lines. `bogie doctor` checks every marker exists exactly once and that every controller it finds is both constructed and mounted.

## Seeing what is mounted

```
bogie routes
```

The table comes after a few lines of startup and Gin noise (trimmed here). This app has a scaffolded `products` and a hand-made `comments` controller:

```
GET      /healthz                        app/controllers.(*Server).SetupRoutes.func1
GET      /products                       app/controllers.(*ProductsController).Index
POST     /products                       app/controllers.(*ProductsController).Create
GET      /products/:id                   app/controllers.(*ProductsController).Show
PATCH    /products/:id                   app/controllers.(*ProductsController).Update
DELETE   /products/:id                   app/controllers.(*ProductsController).Destroy
GET      /comments                       app/controllers.(*CommentsController).Index
GET      /comments/:id                   app/controllers.(*CommentsController).Show
POST     /comments                       app/controllers.(*CommentsController).Create
```

Method, path and handler for every route, in the order it was wired. It boots the app the way `serve` does and prints through Gin's own debug route hook, so the list is what is really mounted, not a guess read off the files. Like Gin's debug output, it prints only in development; in `test` or `production` it exits 0 with nothing. A request no route answers falls through to `public/` and then `public/404.html`: see [Static files and error pages](https://bogie-go.com/docs/static-files.html).

## Giving a controller a dependency

A freshly generated controller holds only a logger. Wiring in a store or a service is three edits, all in files you already own, with no generator for the step itself:

1. Beside the controller, declare the slice it needs (rule 2), only the methods it calls:

   ```
   type commentsStore interface {
   	GetComment(ctx context.Context, id string) (models.Comment, error)
   }
   ```
2. Add a field and a constructor parameter: `Store commentsStore`, `NewCommentsController(store commentsStore, log *slog.Logger)`.
3. On its wire line in `app/application.go`, pass the real thing: `server.Comments = controllers.NewCommentsController(store, log)`. `*adapter.Store` satisfies any interface made of its own methods, so nothing on the store's side changes.

The generated test is a request spec through the whole app: for a stub it checks only that each route is mounted. It looks the method and path up in the application's routes rather than sending a request, so a real `Show` or `Destroy` that answers 404 for a record that is not there does not break it:

```
var _ = Describe("GET /comments/:id", func() {
	It("is mounted", func() {
		Expect(app.Server.Router.Routes()).To(ContainElement(And(
			HaveField("Method", http.MethodGet),
			HaveField("Path", "/comments/:id"),
		)))
	})
})
```

It fails when a route was never registered or the namespace's `routes.go` lost the mount line. Once an action does real work, give it a spec the way a scaffolded controller does, above: arrange records with a factory, send the request, check the answer. See [Request specs](https://bogie-go.com/docs/testing.html#request-specs).

## Namespaces

```
bogie g controller admin/reports index show
```

```
      create  app/controllers/admin_controllers/server.go
      create  app/controllers/admin_controllers/routes.go
      create  app/controllers/admin_controllers/admin_controllers_suite_test.go
      create  app/controllers/admin_controllers/reports_controller.go
      create  app/controllers/admin_controllers/reports_controller_test.go
      insert  app/controllers/application.go: Admin *admin_controllers.Server
      insert  app/application.go: server.Admin = admin_controllers.NewServer(log)
      insert  app/controllers/routes.go: s.Admin.SetupRoutes(&r.RouterGroup)
      insert  app/controllers/admin_controllers/server.go: Reports *ReportsController
      insert  app/application.go: server.Admin.Reports = admin_controllers.NewReportsController(log)
      insert  app/controllers/admin_controllers/routes.go: s.Reports.SetupRoutes(admin)
```

A namespace (everything mounted under `/admin`) is a Go package, `app/controllers/admin_controllers/`, plural like every other directory and written on first use: its own `server.go` with its own `// bogie:controllers` marker, and its own `routes.go` mounting the `/admin` group above its own `// bogie:routes`. The package is registered at the root with the same three lines a controller gets; each controller inside it then gets two more, into the namespace's own files. Middleware the whole namespace shares, an auth check or a shared secret, goes on that group in `routes.go`, so the exposure boundary is visible in one place; `bogie g authentication` writes that middleware, covered in [Authentication](https://bogie-go.com/docs/authentication.html). One level of namespace is supported; a version such as `v1` is a route group inside the namespace's `routes.go`, not a nested namespace. `bogie d controller admin/reports` removes the controller, and the package too once it holds no controller.

## Views: wire structs, never the model

`app/views/posts.go` holds `PostRequest` and `PostResponse`; a model type never doubles as a wire type, so a field added to the database does not silently appear on the wire, and a request can only set the fields its struct has:

```
type PostRequest struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}
```

## Testing a controller

Since v0.4.1, a controller is tested by request specs beside it: Ginkgo specs that send real HTTP through the wired `Server` to the test database, with records arranged by [factories](https://bogie-go.com/docs/testing.html#factories). A scaffold's specs cover list, show, create, update and delete, a 400 for a malformed body, and a 404 for an unknown id. A namespace package gets its own suite file, and its specs go through the same `app`. There is no fake-store controller test any more. The store interface beside the controller still keeps it honest about what it uses. See [Testing and CI](https://bogie-go.com/docs/testing.html).
