mirror of
https://github.com/kataras/iris.git
synced 2025-12-17 18:07:01 +00:00
❤️ awesome and unique features for end-developers are coming...
total refactor of the hero and mvc packages, see README#Next (it's not completed yet) Former-commit-id: b85ae99cbfe5965ba919c1e15cf4989e787982c0
This commit is contained in:
@@ -8,10 +8,6 @@ import (
|
||||
"github.com/kataras/iris/v12/context"
|
||||
"github.com/kataras/iris/v12/core/router"
|
||||
"github.com/kataras/iris/v12/hero"
|
||||
"github.com/kataras/iris/v12/hero/di"
|
||||
"github.com/kataras/iris/v12/macro"
|
||||
|
||||
"github.com/kataras/golog"
|
||||
)
|
||||
|
||||
// BaseController is the optional controller interface, if it's
|
||||
@@ -41,7 +37,7 @@ type shared interface {
|
||||
// it's called once per application.
|
||||
type BeforeActivation interface {
|
||||
shared
|
||||
Dependencies() *di.Values
|
||||
Dependencies() *hero.Container
|
||||
}
|
||||
|
||||
// AfterActivation is being used as the only one input argument of a
|
||||
@@ -54,8 +50,8 @@ type BeforeActivation interface {
|
||||
// it's called once per application.
|
||||
type AfterActivation interface {
|
||||
shared
|
||||
DependenciesReadOnly() ValuesReadOnly
|
||||
Singleton() bool
|
||||
DependenciesReadOnly() []*hero.Dependency
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -66,12 +62,9 @@ var (
|
||||
// ControllerActivator returns a new controller type info description.
|
||||
// Its functionality can be overridden by the end-dev.
|
||||
type ControllerActivator struct {
|
||||
// the router is used on the `Activate` and can be used by end-dev on the `BeforeActivation`
|
||||
// to register any custom controller's methods as handlers.
|
||||
router router.Party
|
||||
app *Application
|
||||
|
||||
macros macro.Macros
|
||||
tmplParamStartIndex int
|
||||
injector *hero.Struct
|
||||
|
||||
// initRef BaseController // the BaseController as it's passed from the end-dev.
|
||||
Value reflect.Value // the BaseController's Value.
|
||||
@@ -85,17 +78,6 @@ type ControllerActivator struct {
|
||||
// `GetRoute/GetRoutes(functionName)`.
|
||||
routes map[string][]*router.Route
|
||||
|
||||
// the bindings that comes from the Engine and the controller's filled fields if any.
|
||||
// Can be bind-ed to the the new controller's fields and method that is fired
|
||||
// on incoming requests.
|
||||
dependencies di.Values
|
||||
sorter di.Sorter
|
||||
|
||||
errorHandler di.ErrorHandler
|
||||
|
||||
// initialized on the first `Handle` or immediately when "servesWebsocket" is true.
|
||||
injector *di.StructInjector
|
||||
|
||||
// true if this controller listens and serves to websocket events.
|
||||
servesWebsocket bool
|
||||
}
|
||||
@@ -103,7 +85,7 @@ type ControllerActivator struct {
|
||||
// NameOf returns the package name + the struct type's name,
|
||||
// it's used to take the full name of an Controller, the `ControllerActivator#Name`.
|
||||
func NameOf(v interface{}) string {
|
||||
elemTyp := di.IndirectType(di.ValueOf(v).Type())
|
||||
elemTyp := indirectType(reflect.ValueOf(v).Type())
|
||||
|
||||
typName := elemTyp.Name()
|
||||
pkgPath := elemTyp.PkgPath()
|
||||
@@ -112,16 +94,15 @@ func NameOf(v interface{}) string {
|
||||
return fullname
|
||||
}
|
||||
|
||||
func newControllerActivator(router router.Party, controller interface{}, dependencies []reflect.Value, sorter di.Sorter, errorHandler di.ErrorHandler) *ControllerActivator {
|
||||
func newControllerActivator(app *Application, controller interface{}) *ControllerActivator {
|
||||
typ := reflect.TypeOf(controller)
|
||||
|
||||
c := &ControllerActivator{
|
||||
// give access to the Router to the end-devs if they need it for some reason,
|
||||
// i.e register done handlers.
|
||||
router: router,
|
||||
macros: *router.Macros(),
|
||||
Value: reflect.ValueOf(controller),
|
||||
Type: typ,
|
||||
app: app,
|
||||
Value: reflect.ValueOf(controller),
|
||||
Type: typ,
|
||||
// the full name of the controller: its type including the package path.
|
||||
fullName: NameOf(controller),
|
||||
// set some methods that end-dev cann't use accidentally
|
||||
@@ -131,14 +112,8 @@ func newControllerActivator(router router.Party, controller interface{}, depende
|
||||
// if a new method is registered via `Handle` its function name
|
||||
// is also appended to that slice.
|
||||
routes: whatReservedMethods(typ),
|
||||
// CloneWithFieldsOf: include the manual fill-ed controller struct's fields to the dependencies.
|
||||
dependencies: di.Values(dependencies).CloneWithFieldsOf(controller),
|
||||
sorter: sorter,
|
||||
errorHandler: errorHandler,
|
||||
}
|
||||
|
||||
fpath, _ := macro.Parse(c.router.GetRelPath(), c.macros)
|
||||
c.tmplParamStartIndex = len(fpath.Params)
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -158,39 +133,6 @@ func whatReservedMethods(typ reflect.Type) map[string][]*router.Route {
|
||||
return routes
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) markAsWebsocket() {
|
||||
c.servesWebsocket = true
|
||||
c.attachInjector()
|
||||
}
|
||||
|
||||
// Dependencies returns the write and read access of the dependencies that are
|
||||
// came from the parent MVC Application, with this you can customize
|
||||
// the dependencies per controller, used at the `BeforeActivation`.
|
||||
func (c *ControllerActivator) Dependencies() *di.Values {
|
||||
return &c.dependencies
|
||||
}
|
||||
|
||||
// ValuesReadOnly returns the read-only access type of the controller's dependencies.
|
||||
// Used at `AfterActivation`.
|
||||
type ValuesReadOnly interface {
|
||||
// Has returns true if a binder responsible to
|
||||
// bind and return a type of "typ" is already registered to this controller.
|
||||
Has(value interface{}) bool
|
||||
// Len returns the length of the values.
|
||||
Len() int
|
||||
// Clone returns a copy of the current values.
|
||||
Clone() di.Values
|
||||
// CloneWithFieldsOf will return a copy of the current values
|
||||
// plus the "s" struct's fields that are filled(non-zero) by the caller.
|
||||
CloneWithFieldsOf(s interface{}) di.Values
|
||||
}
|
||||
|
||||
// DependenciesReadOnly returns the read-only access type of the controller's dependencies.
|
||||
// Used at `AfterActivation`.
|
||||
func (c *ControllerActivator) DependenciesReadOnly() ValuesReadOnly {
|
||||
return c.dependencies
|
||||
}
|
||||
|
||||
// Name returns the full name of the controller, its package name + the type name.
|
||||
// Can used at both `BeforeActivation` and `AfterActivation`.
|
||||
func (c *ControllerActivator) Name() string {
|
||||
@@ -206,7 +148,7 @@ func (c *ControllerActivator) Name() string {
|
||||
//
|
||||
// Can used at both `BeforeActivation` and `AfterActivation`.
|
||||
func (c *ControllerActivator) Router() router.Party {
|
||||
return c.router
|
||||
return c.app.Router
|
||||
}
|
||||
|
||||
// GetRoute returns the first registered route based on the controller's method name.
|
||||
@@ -252,9 +194,23 @@ func (c *ControllerActivator) GetRoutes(methodName string) []*router.Route {
|
||||
// any unexported fields and all fields are services-like, static.
|
||||
func (c *ControllerActivator) Singleton() bool {
|
||||
if c.injector == nil {
|
||||
panic("MVC: Singleton used on an invalid state the API gives access to it only `AfterActivation`, report this as bug")
|
||||
panic("MVC: Singleton called from wrong state the API gives access to it only `AfterActivation`, report this as bug")
|
||||
}
|
||||
return c.injector.Scope == di.Singleton
|
||||
return c.injector.Singleton
|
||||
}
|
||||
|
||||
// DependenciesReadOnly returns a list of dependencies, including the controller's one.
|
||||
func (c *ControllerActivator) DependenciesReadOnly() []*hero.Dependency {
|
||||
if c.injector == nil {
|
||||
panic("MVC: DependenciesReadOnly called from wrong state the API gives access to it only `AfterActivation`, report this as bug")
|
||||
}
|
||||
|
||||
return c.injector.Container.Dependencies
|
||||
}
|
||||
|
||||
// Dependencies returns a value which can manage the controller's dependencies.
|
||||
func (c *ControllerActivator) Dependencies() *hero.Container {
|
||||
return c.app.container
|
||||
}
|
||||
|
||||
// checks if a method is already registered.
|
||||
@@ -268,12 +224,19 @@ func (c *ControllerActivator) isReservedMethod(name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) activate() {
|
||||
c.parseMethods()
|
||||
func (c *ControllerActivator) attachInjector() {
|
||||
if c.injector == nil {
|
||||
c.injector = c.app.container.Struct(c.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) addErr(err error) bool {
|
||||
return c.router.GetReporter().Err(err) != nil
|
||||
func (c *ControllerActivator) markAsWebsocket() {
|
||||
c.servesWebsocket = true
|
||||
c.attachInjector()
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) activate() {
|
||||
c.parseMethods()
|
||||
}
|
||||
|
||||
// register all available, exported methods to handlers if possible.
|
||||
@@ -286,7 +249,7 @@ func (c *ControllerActivator) parseMethods() {
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) parseMethod(m reflect.Method) {
|
||||
httpMethod, httpPath, err := parseMethod(*c.router.Macros(), m, c.isReservedMethod)
|
||||
httpMethod, httpPath, err := parseMethod(c.app.Router.Macros(), m, c.isReservedMethod)
|
||||
if err != nil {
|
||||
if err != errSkip {
|
||||
c.addErr(fmt.Errorf("MVC: fail to parse the route path and HTTP method for '%s.%s': %v", c.fullName, m.Name, err))
|
||||
@@ -298,6 +261,10 @@ func (c *ControllerActivator) parseMethod(m reflect.Method) {
|
||||
c.Handle(httpMethod, httpPath, m.Name)
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) addErr(err error) bool {
|
||||
return c.app.Router.GetReporter().Err(err) != nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -336,35 +303,10 @@ func (c *ControllerActivator) handleMany(method, path, funcName string, override
|
||||
return nil
|
||||
}
|
||||
|
||||
// get the method from the controller type.
|
||||
m, ok := c.Type.MethodByName(funcName)
|
||||
if !ok {
|
||||
c.addErr(fmt.Errorf("MVC: function '%s' doesn't exist inside the '%s' controller",
|
||||
funcName, c.fullName))
|
||||
return nil
|
||||
}
|
||||
|
||||
// parse a route template which contains the parameters organised.
|
||||
tmpl, err := macro.Parse(path, c.macros)
|
||||
if err != nil {
|
||||
c.addErr(fmt.Errorf("MVC: fail to parse the path for '%s.%s': %v", c.fullName, funcName, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
// get the function's input.
|
||||
funcIn := getInputArgsFromFunc(m.Type)
|
||||
// get the path parameters bindings from the template,
|
||||
// use the function's input except the receiver which is the
|
||||
// end-dev's controller pointer.
|
||||
pathParams := getPathParamsForInput(c.tmplParamStartIndex, tmpl.Params, funcIn[1:]...)
|
||||
// get the function's input arguments' bindings.
|
||||
funcDependencies := c.dependencies.Clone()
|
||||
funcDependencies.AddValues(pathParams...)
|
||||
|
||||
handler := c.handlerOf(m, funcDependencies)
|
||||
handler := c.handlerOf(funcName)
|
||||
|
||||
// register the handler now.
|
||||
routes := c.router.HandleMany(method, path, append(middleware, handler)...)
|
||||
routes := c.app.Router.HandleMany(method, path, append(middleware, handler)...)
|
||||
if routes == nil {
|
||||
c.addErr(fmt.Errorf("MVC: unable to register a route for the path for '%s.%s'", c.fullName, funcName))
|
||||
return nil
|
||||
@@ -390,79 +332,21 @@ func (c *ControllerActivator) handleMany(method, path, funcName string, override
|
||||
return routes
|
||||
}
|
||||
|
||||
var emptyIn = []reflect.Value{}
|
||||
|
||||
func (c *ControllerActivator) attachInjector() {
|
||||
if c.injector == nil {
|
||||
c.injector = di.MakeStructInjector(
|
||||
di.ValueOf(c.Value),
|
||||
c.sorter,
|
||||
di.Values(c.dependencies).CloneWithFieldsOf(c.Value)...,
|
||||
)
|
||||
// c.injector = di.Struct(c.Value, c.dependencies...)
|
||||
if !c.servesWebsocket {
|
||||
golog.Debugf("MVC Controller [%s] [Scope=%s]", c.fullName, c.injector.Scope)
|
||||
} else {
|
||||
golog.Debugf("MVC Websocket Controller [%s]", c.fullName)
|
||||
}
|
||||
|
||||
if c.injector.Has {
|
||||
golog.Debugf("Dependencies:\n%s", c.injector.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []reflect.Value) context.Handler {
|
||||
// Remember:
|
||||
// The `Handle->handlerOf` can be called from `BeforeActivation` event
|
||||
// then, the c.injector is nil because
|
||||
// we may not have the dependencies bind-ed yet.
|
||||
// To solve this we're doing a check on the FIRST `Handle`,
|
||||
// if c.injector is nil, then set it with the current bindings,
|
||||
// these bindings can change after, so first add dependencies and after register routes.
|
||||
func (c *ControllerActivator) handlerOf(methodName string) context.Handler {
|
||||
c.attachInjector()
|
||||
|
||||
// fmt.Printf("for %s | values: %s\n", funcName, funcDependencies)
|
||||
funcInjector := di.Func(m.Func, funcDependencies...)
|
||||
funcInjector.ErrorHandler = c.errorHandler
|
||||
handler := c.injector.MethodHandler(methodName)
|
||||
|
||||
// fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length)
|
||||
if funcInjector.Has {
|
||||
golog.Debugf("MVC dependencies of method '%s.%s':\n%s", c.fullName, m.Name, funcInjector.String())
|
||||
}
|
||||
|
||||
var (
|
||||
implementsBase = isBaseController(c.Type)
|
||||
implementsErrorHandler = isErrorHandler(c.Type)
|
||||
hasBindableFields = c.injector.CanInject
|
||||
hasBindableFuncInputs = funcInjector.Has
|
||||
funcHasErrorOut = hasErrorOutArgs(m)
|
||||
|
||||
call = m.Func.Call
|
||||
)
|
||||
|
||||
if !implementsBase && !hasBindableFields && !hasBindableFuncInputs && !implementsErrorHandler {
|
||||
if isBaseController(c.Type) {
|
||||
return func(ctx context.Context) {
|
||||
hero.DispatchFuncResult(ctx, c.errorHandler, call(c.injector.AcquireSlice()))
|
||||
}
|
||||
}
|
||||
ctrl, err := c.injector.Acquire(ctx)
|
||||
if err != nil {
|
||||
if err != hero.ErrStopExecution {
|
||||
c.injector.Container.GetErrorHandler(ctx).HandleError(ctx, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
n := m.Type.NumIn()
|
||||
return func(ctx context.Context) {
|
||||
var (
|
||||
ctrl = c.injector.Acquire()
|
||||
errorHandler = c.errorHandler
|
||||
)
|
||||
|
||||
// inject struct fields first before the BeginRequest and EndRequest, if any,
|
||||
// in order to be able to have access there.
|
||||
if hasBindableFields {
|
||||
c.injector.InjectElem(ctx, ctrl.Elem())
|
||||
}
|
||||
|
||||
// check if has BeginRequest & EndRequest, before try to bind the method's inputs.
|
||||
if implementsBase {
|
||||
// the Interface(). is faster than MethodByName or pre-selected methods.
|
||||
b := ctrl.Interface().(BaseController)
|
||||
// init the request.
|
||||
b.BeginRequest(ctx)
|
||||
@@ -472,28 +356,11 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref
|
||||
return
|
||||
}
|
||||
|
||||
defer b.EndRequest(ctx)
|
||||
handler(ctx)
|
||||
|
||||
b.EndRequest(ctx)
|
||||
}
|
||||
|
||||
if funcHasErrorOut && implementsErrorHandler {
|
||||
errorHandler = ctrl.Interface().(di.ErrorHandler)
|
||||
}
|
||||
|
||||
if hasBindableFuncInputs {
|
||||
// means that ctxValue is not initialized before by the controller's struct injector.
|
||||
|
||||
in := make([]reflect.Value, n)
|
||||
in[0] = ctrl
|
||||
funcInjector.Inject(ctx, &in)
|
||||
|
||||
if ctx.IsStopped() {
|
||||
return // stop as soon as possible, although it would stop later on if `ctx.StopExecution` called.
|
||||
}
|
||||
|
||||
hero.DispatchFuncResult(ctx, errorHandler, call(in))
|
||||
return
|
||||
}
|
||||
|
||||
hero.DispatchFuncResult(ctx, errorHandler, ctrl.Method(m.Index).Call(emptyIn))
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user