Documentation
¶
Index ¶
- Variables
- func UseRepository[T any, ID context.IDType, Filter any](repo Repository[T, ID, Filter], opts ...Option) router.Controller
- func Websocket(controllers ...any) router.Controller
- type Controller
- type DeployedController
- func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) Routing(r router.Router)
- func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) With(relPathWithoutParam string, controllers ...any) *DeployedController[C, Context, Request, Response, ID, Filter, Total]
- func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) WithViews[IndexViewData, CreateViewData, ModelViewData, ListViewData any]() *DeployedController[C, Context, Request, Response, ID, Filter, Total]
- type GrpcController
- type Option
- type PathParam
- type RawPathParam
- type Repository
- type Verb
- type ViewController
- type ViewModel
Constants ¶
This section is empty.
Variables ¶
var DefaultTemplateExtension = ".html"
DefaultTemplateExtension is the default view file extension. Navigate through the `WithViews` method of a deployed controller for more.
Functions ¶
func UseRepository ¶
func UseRepository[T any, ID context.IDType, Filter any](repo Repository[T, ID, Filter], opts ...Option) router.Controller
UseRepository generates the six resource routes over repo:
POST / -> 201 {"id": ...}
GET /{model_id} -> 200 the model
PUT /{model_id} -> 204, or 304 when nothing changed
PATCH /{model_id} -> the same, honouring ?columns=a&columns=b
DELETE /{model_id} -> 204, or 304 when nothing was deleted
POST /list -> 200 a page of models
It is `UseController` without the controller: when a resource's HTTP half adds nothing to its repository, there is no type left to write.
The path parameter name and its macro derive from T and ID exactly as they do for `UseController`, so a uuid.UUID id registers "{model_id:uuid}" and validates before any handler runs. Errors from the repository render through the rest/errors pipeline.
The update routes read their columns through `Context.BindUpdate`, so a column that is not a member of T answers 400 naming it and the members it could have been. The names reaching the repository are still the client's, so a repository that builds SQL from them must map them to its own columns and never interpolate them.
app.Router("/invoices", mvc.UseRepository(invoiceRepository))
Reach for a controller instead as soon as a route needs anything the repository does not do: a mail on create, a computed response, a second store to keep in sync.
func Websocket ¶
func Websocket(controllers ...any) router.Controller
Websocket registers WebSocket controllers and sets up the necessary routes for WebSocket connections and events. It accepts a variadic number of controllers, which can be either struct pointers or functions returning struct pointers.
Each controller can implement standard neffos events as methods. The following events can be implemented by the end-developer: - OnNamespaceConnect(*neffos.NSConn, neffos.Message) error - OnNamespaceConnected(*neffos.NSConn, neffos.Message) error - OnNamespaceDisconnect(*neffos.NSConn, neffos.Message) error - OnRoomJoin(*neffos.NSConn, neffos.Message) error - OnRoomJoined(*neffos.NSConn, neffos.Message) error - OnRoomLeave(*neffos.NSConn, neffos.Message) error - OnRoomLeft(*neffos.NSConn, neffos.Message) error
Any custom method will be translated as a WebSocket event, e.g.: - OnChat(*neffos.NSConn, neffos.Message) error
The function performs the following steps: 1. Creates a new neffos.ConnHandler with an empty namespace map. 2. Iterates over the provided controllers and resolves them using the dependency injection container. 3. Converts each controller to a neffos.StructValue (the reflection form of neffos.Struct) and sets its namespace. 4. Binds the controller's fields if it was a struct pointer. 5. Joins the controller's event handlers to the neffos.ConnHandler. 6. Creates a new neffos.Server with the configured ConnHandler and registers it to the router.
Example usage:
app.Router("/websocket", mvc.Websocket(newWebsocketController))
This will register the WebSocket controller under the /websocket path.
Types ¶
type Controller ¶
type Controller[Context handler.ContextType, Request any, Response any, ID context.IDType, Filter any, Total context.CountType] interface { // POST: /resource Create(Context, Request) (Response, error) // GET: /resource/{id} Get(Context, ID) (Response, error) // PUT: /resource/{id}?columns=column1&columns=column2 Update(Context, ID, Request, ...string) (*Response, bool, error) // DELETE: /resource/{id} Delete(Context, ID) (bool, error) // POST: /resource/list List(ctx Context, filter Filter, limit int, offset int) ([]Response, Total, error) }
Controller is the interface that describes the behavior of a controller. It's used to generate the routes for the controller. The controller may be registered as a dependency before calling `UseController`. If it is not registered, a new instance is created and its exported fields are bound from the dependency injection container.
LIFETIME: a controller is a SINGLETON.
It is resolved once, its exported fields are bound once, and its methods are captured into handlers at registration time. There is no per-request instance and no pooling, so every field is shared, unsynchronised, across all concurrent requests.
Use fields for dependencies only:
type API struct {
Service *Service // fine: set once at registration
user *User // WRONG: one request's user, visible to every other
}
Anything that belongs to a single request belongs on the Context or in a method parameter, never on the controller.
type DeployedController ¶
type DeployedController[C Controller[Context, Request, Response, ID, Filter, Total], Context handler.ContextType, Request any, Response any, ID context.IDType, Filter any, Total context.CountType] struct { Controller C `dep:"-"` // ignore for self-resolving. ModelName string `dep:"-"` // contains filtered or unexported fields }
DeployedController is a controller that has been deployed to a router through the `UseController` function to handle the CRUD routes.
func UseController ¶
func UseController[C Controller[Context, Request, Response, ID, Filter, Total], Context handler.ContextType, Request any, Response any, ID context.IDType, Filter any, Total context.CountType](opts ...Option) *DeployedController[C, Context, Request, Response, ID, Filter, Total]
UseController registers a new controller to the router and sets up the necessary routes for CRUD operations. It accepts a generic type C which must implement the Controller interface.
The function performs the following steps: 1. Creates a new path parameter for the controller's response type and ID type. 2. Registers the path parameter as a dependency to the router. 3. Resolves the controller from the dependency injection container or creates a new instance if not found. 4. Binds the controller's fields if necessary. 5. Calls the controller's custom Routing method if it implements the router.Controller interface, before the CRUD routes are registered, so that an r.Use inside it guards them too. 6. Registers the CRUD routes (Create, Get, Update, Delete, List) to the router.
The optional Options customize the generated routes: `Guard` protects the write routes, `Without` drops routes, `IDParam` renames the path parameter, `BeforeWrite` stamps the decoded body of Create and Update, and `Pagination` declares the List route's sort policy.
The function returns a DeployedController which can be used to add additional routes or controllers under the same path.
Example usage:
app.Router("/stores", mvc.UseController[*StoreController]()).
With("/books", mvc.UseController[*BookController]())
This will register the StoreController under the /stores path and the BookController under the /stores/{store_id}/books path.
func (*DeployedController[C, Context, Request, Response, ID, Filter, Total]) Routing ¶
func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) Routing(r router.Router)
func (*DeployedController[C, Context, Request, Response, ID, Filter, Total]) With ¶
func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) With(relPathWithoutParam string, controllers ...any) *DeployedController[C, Context, Request, Response, ID, Filter, Total]
With registers additional controllers under the same path. It accepts a relative path without parameters and one or more controllers.
func (*DeployedController[C, Context, Request, Response, ID, Filter, Total]) WithViews ¶
func (rc *DeployedController[C, Context, Request, Response, ID, Filter, Total]) WithViews[IndexViewData, CreateViewData, ModelViewData, ListViewData any]() *DeployedController[C, Context, Request, Response, ID, Filter, Total]
WithViews extends the deployed controller with view rendering capabilities. It registers routes for various view-related endpoints and binds them to the corresponding controller methods.
The method is generic over the four view data types and requires the deployed controller to implement the ViewController interface for them; a mismatch panics at registration time. It does not check for a registered view engine, a missing one is only reported when a view is rendered.
The method generates default template names based on the controller's model name and the package-level DefaultTemplateExtension (".html" unless modified). It then creates handlers for each view-related endpoint and registers them with the router.
The following routes are registered: - GET /resource: Renders the index view. - GET /resource/create: Renders the create view. - GET /resource/{id}/details: Renders the details view for a specific resource. - GET /resource/{id}/update: Renders the update view for a specific resource. - GET /resource/{id}/delete: Renders the delete view for a specific resource. - GET /resource/list: Renders the list view.
Example usage:
app.Router("/stores", mvc.UseController[*StoreController]().WithViews[IndexData, CreateData, ModelData, ListData]())
It returns the deployed controller itself for further chaining.
type GrpcController ¶
type GrpcController struct {
// contains filtered or unexported fields
}
GrpcController holds the controller functionality which serves (g)RPC clients over https subprotocol. It accepts the controller ptr to a struct value, the gRPCServer itself, and a strict option which is explained below.
The differences between an GRPC-based controller and a common one are: HTTP verb: only POST (Router.AllowMethods can be used for more), method parsing is disabled: path is the function name as it is, if 'strictMode' option is true then this controller will only serve gRPC-based clients and fires 404 on common HTTP clients, otherwise HTTP clients can send and receive JSON (protos contain json struct fields by-default).
It implements the `Controller` interface.
func GRPC ¶
func GRPC(serverStructPtrValue any) *GrpcController
GRPC returns a new gRPC controller. Example:
ctrl := &myController{}
// New gRPC server to your protos.
grpcServer := grpc.NewServer()
pb.RegisterGreeterServer(grpcServer, ctrl)
app.RegisterDependency(new(myService)) // Optional, register any dependencies.
app.Router("/", mvc.GRPC(ctrl).Server(grpcServer).ServiceName("helloworld.Greeter").Strict(false))
func (*GrpcController) Routing ¶
func (opts *GrpcController) Routing(r router.Router)
Routing registers the controller's methods to the application's router. It parses the controller's methods and registers gRPC handlers to the application. It completes the `Controller` interface.
func (*GrpcController) Server ¶
func (opts *GrpcController) Server(server http.Handler) *GrpcController
Server sets the gRPC server handler. It should be a gRPC Server derives from google's grpc package.
Required.
func (*GrpcController) ServiceName ¶
func (opts *GrpcController) ServiceName(serviceName string) *GrpcController
ServiceName sets the name of the service (used to build the gRPC route path), e.g. "helloworld.Greeter".
Required.
func (*GrpcController) Strict ¶
func (opts *GrpcController) Strict(strict bool) *GrpcController
Strict sets the strict mode. When Strict option is true then this controller will only serve gRPC-based clients and fires 404 on common HTTP clients. Definitely set this to true for streaming.
Defaults to false.
type Option ¶
type Option func(*options)
Option customizes the routes generated by `UseController` and `UseRepository`. Options are plain functional options: pass as many as you need, they apply in order.
func BeforeWrite ¶
BeforeWrite registers a hook which runs on Create and on Update, after the request body is decoded and before the repository or the controller sees it. A non-nil error stops the request and renders through the rest/errors pipeline. Hooks run in registration order.
It is how a value the client must not choose is stamped on every body: a tenant id, an owner, a created-by. The model type is a type parameter, so the hook receives *T directly and no reflection is involved at serve time. A hook whose T is not the type the resource writes panics when the routes are registered, naming both types.
mvc.BeforeWrite(func(ctx iris.Context, v *Invoice) error {
tenantID, ok := auth.ScopeID[string](ctx)
if !ok {
return errors.Unauthenticated
}
v.TenantID = tenantID
return nil
})
func Guard ¶
Guard registers middleware for the write routes only: Create, Update and Delete. Reads (Get and List) stay as they were.
It exists because "everyone may read, only a signed-in user may write" is the common shape, and a router-level Use cannot express it without splitting the resource into two routers.
mvc.UseRepository(repo, mvc.Guard(auth.VerifyHandler()))
func IDParam ¶
IDParam overrides the path parameter name derived from the model type, so that /customers/{customer_id} can be registered as /customers/{id}. The macro (the ":uuid" in "{id:uuid}") still derives from the ID type.
func Pagination ¶
func Pagination(opts ...context.PaginationOption) Option
Pagination declares the list route's sort policy, the options Context.BindPagination and Context.Paginated take. A sort the policy does not allow answers 400 before the controller or the repository runs.
A sort column reaches an ORDER BY clause, so the set of columns a client may name belongs to the endpoint and never to the request.
mvc.UseRepository(repo, mvc.Pagination(iris.AllowSort("created_at", "name")))
mvc.UseRepository(repo, mvc.Pagination(iris.DenySort("this list is ordered by rank")))
The policy reads the decoded filter through its SortRequest method, which context.ListFilter provides, so a filter without one is unaffected.
func Without ¶
Without drops the generated routes of the given verbs. A dropped route is not registered at all, so a request to it answers 404, or 405 when the application enables FireMethodNotAllowed and another method of the same path remains.
An unknown verb panics: it can only be a typo in the program.
mvc.UseRepository(repo, mvc.Without(mvc.Delete))
type PathParam ¶
type PathParam[T any, V context.IDType] struct { *RawPathParam }
PathParam is a dynamic typed path parameter which can be used as a dependency to the controller's fields to the response type the path parameter belongs to. T is the Response type and V is the ID type (string, int, int64, uint64 or uuid.UUID).
func (*PathParam[T, V]) Get ¶
Get returns the path parameter's actual value from the context.
It never panics: a request must not be able to crash the server through a parameter type it controls. When the stored value is already a V the cost is a single type assertion, exactly as before. Only on a type mismatch (the uuid macro stores a uuid.UUID while V is string, or an untyped "{id}" stores a string while V is uuid.UUID, for example) the value is converted into V; if that fails too, the zero V is returned.
type RawPathParam ¶
RawPathParam holds the generated path parameter's name and type.
func GetPathParam ¶
func GetPathParam[T any](ctrl *T) *RawPathParam
GetPathParam returns the path parameter of the controller.
type Repository ¶
type Repository[T any, ID context.IDType, Filter any] interface { // Create stores v and returns its new identifier. Create(ctx stdContext.Context, v T) (ID, error) // Get returns the stored T of the given id. Get(ctx stdContext.Context, id ID) (T, error) // Update stores v over the stored T of the given id, limited to // onlyColumns when the caller named any, and reports whether anything // changed. Update(ctx stdContext.Context, id ID, v T, onlyColumns ...string) (updated bool, err error) // Delete removes the stored T of the given id and reports whether // anything was removed. Delete(ctx stdContext.Context, id ID) (deleted bool, err error) // List returns a page of T matching the filter, and the total count of // the matches, ignoring limit and offset. List(ctx stdContext.Context, filter Filter, limit, offset int) ([]T, int64, error) }
Repository is the persistence half of a resource, the five methods every service's repository already has. Its context is the standard context: a repository never sees Iris.
T is the model, ID its identifier and Filter the value the list route decodes from the request body.
type Verb ¶
type Verb uint8
Verb identifies one of the resource routes that `UseController` and `UseRepository` generate. It is the argument of the `Without` option.
type ViewController ¶
type ViewController[Context handler.ContextType, Request any, Response any, ID context.IDType, Filter any, Total context.CountType, IndexViewData, CreateViewModel, ModelViewData, ListViewData any] interface { Controller[Context, Request, Response, ID, Filter, Total] // GET: /resource IndexView(Context) (IndexViewData, error) // GET: /resource/create CreateView(Context) (CreateViewModel, error) // GET: /resource/{id}/details // // Note that here we could use the same GET /resource/{id} based on the // content-type requested (HTML vs JSON) but we want to keep the separation of concerns. DetailsView(Context, ID) (ModelViewData, error) // GET: /resource/{id}/update UpdateView(Context, ID) (ModelViewData, error) // GET: /resource/{id}/delete DeleteView(Context, ID) (ModelViewData, error) // GET: /resource/list ListView(Context) (ListViewData, error) }
ViewController is an interface that defines methods for rendering views. It extends the Controller interface with additional methods for view rendering.
type ViewModel ¶
type ViewModel[T any] struct { *handler.ViewBuilder }
ViewModel is the view model. It is used as a Response type to render a view with `T` model.