mvc

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2020 License: BSD-3-Clause Imports: 15 Imported by: 1,116

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Try = hero.Try

Try is a type alias for the `hero#Try`, useful to return a result based on two cases: failure(including panics) and a succeess.

Functions

func NameOf

func NameOf(v interface{}) string

NameOf returns the package name + the struct type's name, it's used to take the full name of an Controller, the `ControllerActivator#Name`.

Types

type AfterActivation

type AfterActivation interface {
	Singleton() bool
	DependenciesReadOnly() []*hero.Dependency
	// contains filtered or unexported methods
}

AfterActivation is being used as the only one input argument of a `func(c *Controller) AfterActivation(a mvc.AfterActivation) {}`.

It's being called after the `BeforeActivation`, and after controller's dependencies bind-ed to the fields or the input arguments but before server ran.

It's being used to customize a controller if needed inside the controller itself, it's called once per application.

type Application

type Application struct {

	// This Application's Name. Keep names unique to each other.
	Name string

	Router      router.Party
	Controllers []*ControllerActivator
	// contains filtered or unexported fields
}

Application is the high-level component of the "mvc" package. It's the API that you will be using to register controllers among with their dependencies that your controllers may expecting. It contains the Router(iris.Party) in order to be able to register template layout, middleware, done handlers as you used with the standard Iris APIBuilder.

The Engine is created by the `New` method and it's the dependencies holder and controllers factory.

See `mvc#New` for more.

func Configure

func Configure(party router.Party, configurators ...func(*Application)) *Application

Configure creates a new controller and configures it, this function simply calls the `New(party)` and its `.Configure(configurators...)`.

A call of `mvc.New(app.Party("/path").Configure(buildMyMVC)` is equal to

`mvc.Configure(app.Party("/path"), buildMyMVC)`.

Read more at `New() Application` and `Application#Configure` methods.

func New

func New(party router.Party) *Application

New returns a new mvc Application based on a "party". Application creates a new engine which is responsible for binding the dependencies and creating and activating the app's controller(s).

Example: `New(app.Party("/todo"))` or `New(app)` as it's the same as `New(app.Party("/"))`.

func (*Application) Clone

func (app *Application) Clone(party router.Party) *Application

Clone returns a new mvc Application which has the dependencies of the current mvc Application's `Dependencies` and its `ErrorHandler`.

Example: `.Clone(app.Party("/path")).Handle(new(TodoSubController))`.

func (*Application) Configure

func (app *Application) Configure(configurators ...func(*Application)) *Application

Configure can be used to pass one or more functions that accept this Application, use this to add dependencies and controller(s).

Example: `New(app.Party("/todo")).Configure(func(mvcApp *mvc.Application){...})`.

func (*Application) GetNamespaces

func (app *Application) GetNamespaces() websocket.Namespaces

GetNamespaces completes the websocket ConnHandler interface. It returns a collection of namespace and events that were registered through `HandleWebsocket` controllers.

func (*Application) Handle

func (app *Application) Handle(controller interface{}, options ...Option) *Application

Handle serves a controller for the current mvc application's Router. It accept any custom struct which its functions will be transformed to routes.

If "controller" has `BeforeActivation(b mvc.BeforeActivation)` or/and `AfterActivation(a mvc.AfterActivation)` then these will be called between the controller's `.activate`, use those when you want to modify the controller before or/and after the controller will be registered to the main Iris Application.

It returns this mvc Application.

Usage: `.Handle(new(TodoController))`.

Controller accepts a sub router and registers any custom struct as controller, if struct doesn't have any compatible methods neither are registered via `ControllerActivator`'s `Handle` method then the controller is not registered at all.

A Controller may have one or more methods that are wrapped to a handler and registered as routes before the server ran. The controller's method can accept any input argument that are previously binded via the dependencies or route's path accepts dynamic path parameters. The controller's fields are also bindable via the dependencies, either a static value (service) or a function (dynamically) which accepts a context and returns a single value (this type is being used to find the relative field or method's input argument).

func(c *ExampleController) Get() string | (string, string) | (string, int) | int | (int, string | (string, error) | bool | (any, bool) | error | (int, error) | (customStruct, error) | customStruct | (customStruct, int) | (customStruct, string) | Result or (Result, error) where Get is an HTTP Method func.

Default behavior can be changed through second, variadic, variable "options", e.g. Handle(controller, GRPC {Server: grpcServer, Strict: true})

Examples at: https://github.com/kataras/iris/tree/master/_examples/mvc

func (*Application) HandleError

func (app *Application) HandleError(handler func(ctx *context.Context, err error)) *Application

HandleError registers a `hero.ErrorHandlerFunc` which will be fired when application's controllers' functions returns an non-nil error. Each controller can override it by implementing the `hero.ErrorHandler`.

func (*Application) HandleWebsocket

func (app *Application) HandleWebsocket(controller interface{}) *websocket.Struct

HandleWebsocket handles a websocket specific controller. Its exported methods are the events. If a "Namespace" field or method exists then namespace is set, otherwise empty namespace. Note that a websocket controller is registered and ran under a specific connection connected to a namespace and it cannot send HTTP responses on that state. However all static and dynamic dependency injection features are working, as expected, like any regular MVC Controller.

func (*Application) Party

func (app *Application) Party(relativePath string, middleware ...context.Handler) *Application

Party returns a new child mvc Application based on the current path + "relativePath". The new mvc Application has the same dependencies of the current mvc Application, until otherwise specified later manually.

The router's root path of this child will be the current mvc Application's root path + "relativePath".

func (*Application) Register

func (app *Application) Register(dependencies ...interface{}) *Application

Register appends one or more values as dependencies. The value can be a single struct value-instance or a function which has one input and one output, the input should be an `iris.Context` and the output can be any type, that output type will be bind-ed to the controller's field, if matching or to the controller's methods, if matching.

These dependencies "dependencies" can be changed per-controller as well, via controller's `BeforeActivation` and `AfterActivation` methods, look the `Handle` method for more.

It returns this Application.

Example: `.Register(loggerService{prefix: "dev"}, func(ctx iris.Context) User {...})`.

func (*Application) SetName

func (app *Application) SetName(appName string) *Application

SetName sets a unique name to this MVC Application. Used for logging, not used in runtime yet, but maybe useful for future features.

It returns this Application.

type BaseController

type BaseController interface {
	BeginRequest(*context.Context)
	EndRequest(*context.Context)
}

BaseController is the optional controller interface, if it's completed by the end controller then the BeginRequest and EndRequest are called between the controller's method responsible for the incoming request.

type BeforeActivation

type BeforeActivation interface {
	Dependencies() *hero.Container
	// contains filtered or unexported methods
}

BeforeActivation is being used as the only one input argument of a `func(c *Controller) BeforeActivation(b mvc.BeforeActivation) {}`.

It's being called before the controller's dependencies binding to the fields or the input arguments but before server ran.

It's being used to customize a controller if needed inside the controller itself, it's called once per application.

type ControllerActivator

type ControllerActivator struct {

	// initRef BaseController // the BaseController as it's passed from the end-dev.
	Value reflect.Value // the BaseController's Value.
	Type  reflect.Type  // raw type of the BaseController (initRef).

	// BeginHandlers is a slice of middleware for this controller.
	// These handlers will be prependend to each one of
	// the route that this controller will register(Handle/HandleMany/struct methods)
	// to the targeted Party.
	// Look the `Use` method too.
	BeginHandlers context.Handlers
	// contains filtered or unexported fields
}

ControllerActivator returns a new controller type info description. Its functionality can be overridden by the end-dev.

func (*ControllerActivator) Activated

func (c *ControllerActivator) Activated() bool

Activated can be called to skip the internal method parsing.

func (*ControllerActivator) Dependencies

func (c *ControllerActivator) Dependencies() *hero.Container

Dependencies returns a value which can manage the controller's dependencies.

func (*ControllerActivator) DependenciesReadOnly

func (c *ControllerActivator) DependenciesReadOnly() []*hero.Dependency

DependenciesReadOnly returns a list of dependencies, including the controller's one.

func (*ControllerActivator) GetRoute

func (c *ControllerActivator) GetRoute(methodName string) *router.Route

GetRoute returns the first registered route based on the controller's method name. It can be used to change the route's name, which is useful for reverse routing inside views. Custom routes can be registered with `Handle`, which returns the *Route. This method exists mostly for the automatic method parsing based on the known patterns inside a controller.

A check for `nil` is necessary for unregistered methods.

See `GetRoutes` and `Handle` too.

func (*ControllerActivator) GetRoutes

func (c *ControllerActivator) GetRoutes(methodName string) []*router.Route

GetRoutes returns one or more registered route based on the controller's method name. It can be used to change the route's name, which is useful for reverse routing inside views. Custom routes can be registered with `Handle`, which returns the *Route. This method exists mostly for the automatic method parsing based on the known patterns inside a controller.

A check for `nil` is necessary for unregistered methods.

See `Handle` too.

func (*ControllerActivator) Handle

func (c *ControllerActivator) Handle(method, path, funcName string, middleware ...context.Handler) *router.Route

Handle registers a route based on a http method, the route's path and a function name that belongs to the controller, it accepts a forth, optionally, variadic parameter which is the before handlers.

Just like `Party#Handle`, it returns the `*router.Route`, if failed then it logs the errors and it returns nil, you can check the errors programmatically by the `Party#GetReporter`.

Handle will add a route to the "funcName".

func (*ControllerActivator) HandleMany

func (c *ControllerActivator) HandleMany(method, path, funcName string, middleware ...context.Handler) []*router.Route

HandleMany like `Handle` but can register more than one path and HTTP method routes separated by whitespace on the same controller's method. Keep note that if the controller's method input arguments are path parameters dependencies they should match with each of the given paths.

Just like `Party#HandleMany`:, it returns the `[]*router.Routes`. Usage:

func (*Controller) BeforeActivation(b mvc.BeforeActivation) {
	b.HandleMany("GET", "/path /path1" /path2", "HandlePath")
}

HandleMany will override any routes of this "funcName".

func (*ControllerActivator) Name

func (c *ControllerActivator) Name() string

Name returns the full name of the controller, its package name + the type name. Can used at both `BeforeActivation` and `AfterActivation`.

func (*ControllerActivator) Router

func (c *ControllerActivator) Router() router.Party

Router is the standard Iris router's public API. With this you can register middleware, view layouts, subdomains, serve static files and even add custom standard iris handlers as normally.

This Router is the router instance that came from the parent MVC Application, it's the `app.Party(...)` argument.

Can used at both `BeforeActivation` and `AfterActivation`.

func (*ControllerActivator) Singleton

func (c *ControllerActivator) Singleton() bool

Singleton returns new if all incoming clients' requests have the same controller instance. This is done automatically by iris to reduce the creation of a new controller on each request, if the controller doesn't contain any unexported fields and all fields are services-like, static.

func (*ControllerActivator) Use

Use registers a middleware for this Controller. It appends one or more handlers to the `BeginHandlers`. It's like the `Party.Use` but specifically for the routes that this controller will register to the targeted `Party`.

type DeprecationOptions

type DeprecationOptions = versioning.DeprecationOptions

DeprecationOptions describes the deprecation headers key-values. Is a type alias for the `versioning#DeprecationOptions`.

See `Deprecated` package-level option.

type GRPC

type GRPC struct {
	// Server is required and should be gRPC Server derives from google's grpc package.
	Server http.Handler
	// ServiceName is required and should be the name of the service (used to build the gRPC route path),
	// e.g. "helloworld.Greeter".
	// For a controller's method of "SayHello" and ServiceName "helloworld.Greeter",
	// both gRPC and common HTTP request path is: "/helloworld.Greeter/SayHello".
	//
	// Tip: the ServiceName can be fetched through proto's file descriptor, e.g.
	// serviceName := pb.File_helloworld_proto.Services().Get(0).FullName().
	ServiceName string

	// When Strict option is true then this controller will only serve gRPC-based clients
	// and fires 404 on common HTTP clients.
	Strict bool
}

GRPC registers a controller which serves gRPC clients. It accepts the controller ptr to a struct value, the gRPCServer itself, and a strict option which is explained below.

The differences by a common controller are: HTTP verb: only POST (Party.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).

func (GRPC) Apply

func (g GRPC) Apply(c *ControllerActivator)

Apply parses the controller's methods and registers gRPC handlers to the application.

type Option

type Option interface {
	Apply(*ControllerActivator)
}

Option is an interface which does contain a single `Apply` method that accepts a `ControllerActivator`. It can be passed on `Application.Handle` method to mdoify the behavior right after the `BeforeActivation` state.

See `GRPC` package-level structure and `Version` package-level function too.

type OptionFunc

type OptionFunc func(*ControllerActivator)

OptionFunc is the functional type of `Option`. Read `Option` docs.

func Deprecated

func Deprecated(options DeprecationOptions) OptionFunc

Deprecated marks a specific Controller as a deprecated one. Deprecated can be used to tell the clients that a newer version of that specific resource is available instead.

func Version

func Version(version string) OptionFunc

Version returns a valid `Option` that can be passed to the `Application.Handle` method. It requires a specific "version" constraint for a Controller, e.g. ">1, <=2" or just "1".

Usage:

m := mvc.New(dataRouter)
m.Handle(new(v1Controller), mvc.Version("1"), mvc.Deprecated(mvc.DeprecationOptions{}))
m.Handle(new(v2Controller), mvc.Version("2.3"))
m.Handle(new(v3Controller), mvc.Version(">=3, <4"))
m.Handle(new(noVersionController))

See the `versioning` package's documentation for more information on how the version is extracted from incoming requests.

Note that this Option will set the route register rule to `RouteOverlap`.

func (OptionFunc) Apply

func (opt OptionFunc) Apply(c *ControllerActivator)

Apply completes the `Option` interface.

type Response

type Response = hero.Response

Response is a type alias for the `hero#Response`, useful for output controller's methods.

type Result

type Result = hero.Result

Result is a type alias for the `hero#Result`, useful for output controller's methods.

type View

type View = hero.View

View is a type alias for the `hero#View`, useful for output controller's methods.

Jump to

Keyboard shortcuts

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