controller.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package mvc
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "github.com/kataras/iris/context"
  7. "github.com/kataras/iris/core/router"
  8. "github.com/kataras/iris/core/router/macro"
  9. "github.com/kataras/iris/hero"
  10. "github.com/kataras/iris/hero/di"
  11. "github.com/kataras/golog"
  12. )
  13. // BaseController is the optional controller interface, if it's
  14. // completed by the end controller then the BeginRequest and EndRequest
  15. // are called between the controller's method responsible for the incoming request.
  16. type BaseController interface {
  17. BeginRequest(context.Context)
  18. EndRequest(context.Context)
  19. }
  20. type shared interface {
  21. Name() string
  22. Router() router.Party
  23. GetRoute(methodName string) *router.Route
  24. Handle(httpMethod, path, funcName string, middleware ...context.Handler) *router.Route
  25. }
  26. // BeforeActivation is being used as the onle one input argument of a
  27. // `func(c *Controller) BeforeActivation(b mvc.BeforeActivation) {}`.
  28. //
  29. // It's being called before the controller's dependencies binding to the fields or the input arguments
  30. // but before server ran.
  31. //
  32. // It's being used to customize a controller if needed inside the controller itself,
  33. // it's called once per application.
  34. type BeforeActivation interface {
  35. shared
  36. Dependencies() *di.Values
  37. }
  38. // AfterActivation is being used as the onle one input argument of a
  39. // `func(c *Controller) AfterActivation(a mvc.AfterActivation) {}`.
  40. //
  41. // It's being called after the `BeforeActivation`,
  42. // and after controller's dependencies binded to the fields or the input arguments but before server ran.
  43. //
  44. // It's being used to customize a controller if needed inside the controller itself,
  45. // it's called once per application.
  46. type AfterActivation interface {
  47. shared
  48. DependenciesReadOnly() ValuesReadOnly
  49. Singleton() bool
  50. }
  51. var (
  52. _ BeforeActivation = (*ControllerActivator)(nil)
  53. _ AfterActivation = (*ControllerActivator)(nil)
  54. )
  55. // ControllerActivator returns a new controller type info description.
  56. // Its functionality can be overridden by the end-dev.
  57. type ControllerActivator struct {
  58. // the router is used on the `Activate` and can be used by end-dev on the `BeforeActivation`
  59. // to register any custom controller's methods as handlers.
  60. router router.Party
  61. // initRef BaseController // the BaseController as it's passed from the end-dev.
  62. Value reflect.Value // the BaseController's Value.
  63. Type reflect.Type // raw type of the BaseController (initRef).
  64. // FullName it's the last package path segment + "." + the Name.
  65. // i.e: if login-example/user/controller.go, the FullName is "user.Controller".
  66. fullName string
  67. // the already-registered routes, key = the controller's function name.
  68. // End-devs can change some properties of the *Route on the `BeforeActivator` by using the
  69. // `GetRoute(functionName)`. It's also protects for duplicatations.
  70. routes map[string]*router.Route
  71. // the bindings that comes from the Engine and the controller's filled fields if any.
  72. // Can be binded to the the new controller's fields and method that is fired
  73. // on incoming requests.
  74. dependencies di.Values
  75. // initialized on the first `Handle`.
  76. injector *di.StructInjector
  77. }
  78. // NameOf returns the package name + the struct type's name,
  79. // it's used to take the full name of an Controller, the `ControllerActivator#Name`.
  80. func NameOf(v interface{}) string {
  81. elemTyp := di.IndirectType(di.ValueOf(v).Type())
  82. typName := elemTyp.Name()
  83. pkgPath := elemTyp.PkgPath()
  84. fullname := pkgPath[strings.LastIndexByte(pkgPath, '/')+1:] + "." + typName
  85. return fullname
  86. }
  87. func newControllerActivator(router router.Party, controller interface{}, dependencies []reflect.Value) *ControllerActivator {
  88. typ := reflect.TypeOf(controller)
  89. c := &ControllerActivator{
  90. // give access to the Router to the end-devs if they need it for some reason,
  91. // i.e register done handlers.
  92. router: router,
  93. Value: reflect.ValueOf(controller),
  94. Type: typ,
  95. // the full name of the controller: its type including the package path.
  96. fullName: NameOf(controller),
  97. // set some methods that end-dev cann't use accidentally
  98. // to register a route via the `Handle`,
  99. // all available exported and compatible methods
  100. // are being appended to the slice at the `parseMethods`,
  101. // if a new method is registered via `Handle` its function name
  102. // is also appended to that slice.
  103. routes: whatReservedMethods(typ),
  104. // CloneWithFieldsOf: include the manual fill-ed controller struct's fields to the dependencies.
  105. dependencies: di.Values(dependencies).CloneWithFieldsOf(controller),
  106. }
  107. return c
  108. }
  109. func whatReservedMethods(typ reflect.Type) map[string]*router.Route {
  110. methods := []string{"BeforeActivation", "AfterActivation"}
  111. // BeforeActivatior/AfterActivation are not routes but they are
  112. // reserved names*
  113. if isBaseController(typ) {
  114. methods = append(methods, "BeginRequest", "EndRequest")
  115. }
  116. routes := make(map[string]*router.Route, len(methods))
  117. for _, m := range methods {
  118. routes[m] = &router.Route{}
  119. }
  120. return routes
  121. }
  122. // Dependencies returns the write and read access of the dependencies that are
  123. // came from the parent MVC Application, with this you can customize
  124. // the dependencies per controller, used at the `BeforeActivation`.
  125. func (c *ControllerActivator) Dependencies() *di.Values {
  126. return &c.dependencies
  127. }
  128. // ValuesReadOnly returns the read-only access type of the controller's dependencies.
  129. // Used at `AfterActivation`.
  130. type ValuesReadOnly interface {
  131. // Has returns true if a binder responsible to
  132. // bind and return a type of "typ" is already registered to this controller.
  133. Has(value interface{}) bool
  134. // Len returns the length of the values.
  135. Len() int
  136. // Clone returns a copy of the current values.
  137. Clone() di.Values
  138. // CloneWithFieldsOf will return a copy of the current values
  139. // plus the "s" struct's fields that are filled(non-zero) by the caller.
  140. CloneWithFieldsOf(s interface{}) di.Values
  141. }
  142. // DependenciesReadOnly returns the read-only access type of the controller's dependencies.
  143. // Used at `AfterActivation`.
  144. func (c *ControllerActivator) DependenciesReadOnly() ValuesReadOnly {
  145. return c.dependencies
  146. }
  147. // Name returns the full name of the controller, its package name + the type name.
  148. // Can used at both `BeforeActivation` and `AfterActivation`.
  149. func (c *ControllerActivator) Name() string {
  150. return c.fullName
  151. }
  152. // Router is the standard Iris router's public API.
  153. // With this you can register middleware, view layouts, subdomains, serve static files
  154. // and even add custom standard iris handlers as normally.
  155. //
  156. // This Router is the router instance that came from the parent MVC Application,
  157. // it's the `app.Party(...)` argument.
  158. //
  159. // Can used at both `BeforeActivation` and `AfterActivation`.
  160. func (c *ControllerActivator) Router() router.Party {
  161. return c.router
  162. }
  163. // GetRoute returns a registered route based on the controller's method name.
  164. // It can be used to change the route's name, which is useful for reverse routing
  165. // inside views. Custom routes can be registered with `Handle`, which returns the *Route.
  166. // This method exists mostly for the automatic method parsing based on the known patterns
  167. // inside a controller.
  168. //
  169. // A check for `nil` is necessary for unregistered methods.
  170. //
  171. // See `Handle` too.
  172. func (c *ControllerActivator) GetRoute(methodName string) *router.Route {
  173. for name, route := range c.routes {
  174. if name == methodName {
  175. return route
  176. }
  177. }
  178. return nil
  179. }
  180. // Singleton returns new if all incoming clients' requests
  181. // have the same controller instance.
  182. // This is done automatically by iris to reduce the creation
  183. // of a new controller on each request, if the controller doesn't contain
  184. // any unexported fields and all fields are services-like, static.
  185. func (c *ControllerActivator) Singleton() bool {
  186. if c.injector == nil {
  187. panic("MVC: Singleton used on an invalid state the API gives access to it only `AfterActivation`, report this as bug")
  188. }
  189. return c.injector.Scope == di.Singleton
  190. }
  191. // checks if a method is already registered.
  192. func (c *ControllerActivator) isReservedMethod(name string) bool {
  193. for methodName := range c.routes {
  194. if methodName == name {
  195. return true
  196. }
  197. }
  198. return false
  199. }
  200. func (c *ControllerActivator) activate() {
  201. c.parseMethods()
  202. }
  203. func (c *ControllerActivator) addErr(err error) bool {
  204. return c.router.GetReporter().AddErr(err)
  205. }
  206. // register all available, exported methods to handlers if possible.
  207. func (c *ControllerActivator) parseMethods() {
  208. n := c.Type.NumMethod()
  209. for i := 0; i < n; i++ {
  210. m := c.Type.Method(i)
  211. c.parseMethod(m)
  212. }
  213. }
  214. func (c *ControllerActivator) parseMethod(m reflect.Method) {
  215. httpMethod, httpPath, err := parseMethod(m, c.isReservedMethod)
  216. if err != nil {
  217. if err != errSkip {
  218. c.addErr(fmt.Errorf("MVC: fail to parse the route path and HTTP method for '%s.%s': %v", c.fullName, m.Name, err))
  219. }
  220. return
  221. }
  222. c.Handle(httpMethod, httpPath, m.Name)
  223. }
  224. // Handle registers a route based on a http method, the route's path
  225. // and a function name that belongs to the controller, it accepts
  226. // a forth, optionally, variadic parameter which is the before handlers.
  227. //
  228. // Just like `APIBuilder`, it returns the `*router.Route`, if failed
  229. // then it logs the errors and it returns nil, you can check the errors
  230. // programmatically by the `APIBuilder#GetReporter`.
  231. func (c *ControllerActivator) Handle(method, path, funcName string, middleware ...context.Handler) *router.Route {
  232. if method == "" || path == "" || funcName == "" ||
  233. c.isReservedMethod(funcName) {
  234. // isReservedMethod -> if it's already registered
  235. // by a previous Handle or analyze methods internally.
  236. return nil
  237. }
  238. // get the method from the controller type.
  239. m, ok := c.Type.MethodByName(funcName)
  240. if !ok {
  241. c.addErr(fmt.Errorf("MVC: function '%s' doesn't exist inside the '%s' controller",
  242. funcName, c.fullName))
  243. return nil
  244. }
  245. // parse a route template which contains the parameters organised.
  246. tmpl, err := macro.Parse(path, c.router.Macros())
  247. if err != nil {
  248. c.addErr(fmt.Errorf("MVC: fail to parse the path for '%s.%s': %v", c.fullName, funcName, err))
  249. return nil
  250. }
  251. // get the function's input.
  252. funcIn := getInputArgsFromFunc(m.Type)
  253. // get the path parameters bindings from the template,
  254. // use the function's input except the receiver which is the
  255. // end-dev's controller pointer.
  256. pathParams := getPathParamsForInput(tmpl.Params, funcIn[1:]...)
  257. // get the function's input arguments' bindings.
  258. funcDependencies := c.dependencies.Clone()
  259. funcDependencies.AddValues(pathParams...)
  260. handler := c.handlerOf(m, funcDependencies)
  261. // register the handler now.
  262. route := c.router.Handle(method, path, append(middleware, handler)...)
  263. if route == nil {
  264. c.addErr(fmt.Errorf("MVC: unable to register a route for the path for '%s.%s'", c.fullName, funcName))
  265. return nil
  266. }
  267. // change the main handler's name in order to respect the controller's and give
  268. // a proper debug message.
  269. route.MainHandlerName = fmt.Sprintf("%s.%s", c.fullName, funcName)
  270. // add this as a reserved method name in order to
  271. // be sure that the same func will not be registered again,
  272. // even if a custom .Handle later on.
  273. c.routes[funcName] = route
  274. return route
  275. }
  276. var emptyIn = []reflect.Value{}
  277. func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []reflect.Value) context.Handler {
  278. // Remember:
  279. // The `Handle->handlerOf` can be called from `BeforeActivation` event
  280. // then, the c.injector is nil because
  281. // we may not have the dependencies binded yet.
  282. // To solve this we're doing a check on the FIRST `Handle`,
  283. // if c.injector is nil, then set it with the current bindings,
  284. // these bindings can change after, so first add dependencies and after register routes.
  285. if c.injector == nil {
  286. c.injector = di.Struct(c.Value, c.dependencies...)
  287. if c.injector.Has {
  288. golog.Debugf("MVC dependencies of '%s':\n%s", c.fullName, c.injector.String())
  289. }
  290. }
  291. // fmt.Printf("for %s | values: %s\n", funcName, funcDependencies)
  292. funcInjector := di.Func(m.Func, funcDependencies...)
  293. // fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length)
  294. if funcInjector.Has {
  295. golog.Debugf("MVC dependencies of method '%s.%s':\n%s", c.fullName, m.Name, funcInjector.String())
  296. }
  297. var (
  298. implementsBase = isBaseController(c.Type)
  299. hasBindableFields = c.injector.CanInject
  300. hasBindableFuncInputs = funcInjector.Has
  301. call = m.Func.Call
  302. )
  303. if !implementsBase && !hasBindableFields && !hasBindableFuncInputs {
  304. return func(ctx context.Context) {
  305. hero.DispatchFuncResult(ctx, call(c.injector.AcquireSlice()))
  306. }
  307. }
  308. n := m.Type.NumIn()
  309. return func(ctx context.Context) {
  310. var (
  311. ctrl = c.injector.Acquire()
  312. ctxValue reflect.Value
  313. )
  314. // inject struct fields first before the BeginRequest and EndRequest, if any,
  315. // in order to be able to have access there.
  316. if hasBindableFields {
  317. ctxValue = reflect.ValueOf(ctx)
  318. c.injector.InjectElem(ctrl.Elem(), ctxValue)
  319. }
  320. // check if has BeginRequest & EndRequest, before try to bind the method's inputs.
  321. if implementsBase {
  322. // the Interface(). is faster than MethodByName or pre-selected methods.
  323. b := ctrl.Interface().(BaseController)
  324. // init the request.
  325. b.BeginRequest(ctx)
  326. // if begin request stopped the execution.
  327. if ctx.IsStopped() {
  328. return
  329. }
  330. defer b.EndRequest(ctx)
  331. }
  332. if hasBindableFuncInputs {
  333. // means that ctxValue is not initialized before by the controller's struct injector.
  334. if !hasBindableFields {
  335. ctxValue = reflect.ValueOf(ctx)
  336. }
  337. in := make([]reflect.Value, n, n)
  338. in[0] = ctrl
  339. funcInjector.Inject(&in, ctxValue)
  340. hero.DispatchFuncResult(ctx, call(in))
  341. return
  342. }
  343. hero.DispatchFuncResult(ctx, ctrl.Method(m.Index).Call(emptyIn))
  344. }
  345. }