mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 15:30:36 +01:00
fix all _examples to the newest mvc, add comments to those examples and add a package-level .Configure in order to make it easier for new users. Add a deprecated panic if app.Controller is used with a small tutorial and future resource link so they can re-write their mvc app's definitions
Former-commit-id: bf07696041be9e3d178ce3c42ccec2df4bfdb2af
This commit is contained in:
parent
fd0f3ed6cb
commit
b78698f6c0
|
@ -6,6 +6,7 @@ import (
|
|||
"github.com/kataras/iris/_examples/structuring/login-mvc-single-responsibility-package/user"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
|
@ -19,13 +20,7 @@ func main() {
|
|||
|
||||
app.StaticWeb("/public", "./public")
|
||||
|
||||
manager := sessions.New(sessions.Config{
|
||||
Cookie: "sessioncookiename",
|
||||
Expires: 24 * time.Hour,
|
||||
})
|
||||
users := user.NewDataSource()
|
||||
|
||||
app.Controller("/user", new(user.Controller), manager, users)
|
||||
mvc.Configure(app, configureMVC)
|
||||
|
||||
// http://localhost:8080/user/register
|
||||
// http://localhost:8080/user/login
|
||||
|
@ -35,9 +30,22 @@ func main() {
|
|||
app.Run(iris.Addr(":8080"), configure)
|
||||
}
|
||||
|
||||
func configureMVC(app *mvc.Application) {
|
||||
manager := sessions.New(sessions.Config{
|
||||
Cookie: "sessioncookiename",
|
||||
Expires: 24 * time.Hour,
|
||||
})
|
||||
|
||||
userApp := app.NewChild(app.Router.Party("/user"))
|
||||
userApp.AddDependencies(
|
||||
user.NewDataSource(),
|
||||
mvc.Session(manager),
|
||||
)
|
||||
userApp.Register(new(user.Controller))
|
||||
}
|
||||
|
||||
func configure(app *iris.Application) {
|
||||
app.Configure(
|
||||
iris.WithoutServerError(iris.ErrServerClosed),
|
||||
iris.WithCharset("UTF-8"),
|
||||
)
|
||||
}
|
||||
|
|
|
@ -6,51 +6,52 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
const sessionIDKey = "UserID"
|
||||
|
||||
// paths
|
||||
const (
|
||||
PathLogin = "/user/login"
|
||||
PathLogout = "/user/logout"
|
||||
)
|
||||
|
||||
// the session key for the user id comes from the Session.
|
||||
const (
|
||||
sessionIDKey = "UserID"
|
||||
var (
|
||||
PathLogin = mvc.Response{Path: "/user/login"}
|
||||
PathLogout = mvc.Response{Path: "/user/logout"}
|
||||
)
|
||||
|
||||
// AuthController is the user authentication controller, a custom shared controller.
|
||||
type AuthController struct {
|
||||
iris.SessionController
|
||||
// context is auto-binded if struct depends on this,
|
||||
// in this controller we don't we do everything with mvc-style,
|
||||
// and that's neither the 30% of its features.
|
||||
// Ctx iris.Context
|
||||
|
||||
Source *DataSource
|
||||
User Model `iris:"model"`
|
||||
Source *DataSource
|
||||
Session *sessions.Session
|
||||
|
||||
// the whole controller is request-scoped because we already depend on Session, so
|
||||
// this will be new for each new incoming request, BeginRequest sets that based on the session.
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// BeginRequest saves login state to the context, the user id.
|
||||
func (c *AuthController) BeginRequest(ctx iris.Context) {
|
||||
c.SessionController.BeginRequest(ctx)
|
||||
c.UserID, _ = c.Session.GetInt64(sessionIDKey)
|
||||
}
|
||||
|
||||
if userID := c.Session.Get(sessionIDKey); userID != nil {
|
||||
ctx.Values().Set(sessionIDKey, userID)
|
||||
// EndRequest is here just to complete the BaseController
|
||||
// in order to be tell iris to call the `BeginRequest` before the main method.
|
||||
func (c *AuthController) EndRequest(ctx iris.Context) {}
|
||||
|
||||
func (c *AuthController) fireError(err error) mvc.View {
|
||||
return mvc.View{
|
||||
Code: iris.StatusBadRequest,
|
||||
Name: "shared/error.html",
|
||||
Data: iris.Map{"Title": "User Error", "Message": strings.ToUpper(err.Error())},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *AuthController) fireError(err error) {
|
||||
if err != nil {
|
||||
c.Ctx.Application().Logger().Debug(err.Error())
|
||||
|
||||
c.Status = 400
|
||||
c.Data["Title"] = "User Error"
|
||||
c.Data["Message"] = strings.ToUpper(err.Error())
|
||||
c.Tmpl = "shared/error.html"
|
||||
}
|
||||
}
|
||||
|
||||
func (c *AuthController) redirectTo(id int64) {
|
||||
if id > 0 {
|
||||
c.Path = "/user/" + strconv.Itoa(int(id))
|
||||
}
|
||||
func (c *AuthController) redirectTo(id int64) mvc.Response {
|
||||
return mvc.Response{Path: "/user/" + strconv.Itoa(int(id))}
|
||||
}
|
||||
|
||||
func (c *AuthController) createOrUpdate(firstname, username, password string) (user Model, err error) {
|
||||
|
@ -75,8 +76,8 @@ func (c *AuthController) createOrUpdate(firstname, username, password string) (u
|
|||
|
||||
func (c *AuthController) isLoggedIn() bool {
|
||||
// we don't search by session, we have the user id
|
||||
// already by the `SaveState` middleware.
|
||||
return c.Values.Get(sessionIDKey) != nil
|
||||
// already by the `BeginRequest` middleware.
|
||||
return c.UserID > 0
|
||||
}
|
||||
|
||||
func (c *AuthController) verify(username, password string) (user Model, err error) {
|
||||
|
@ -101,24 +102,9 @@ func (c *AuthController) verify(username, password string) (user Model, err erro
|
|||
// if logged in then destroy the session
|
||||
// and redirect to the login page
|
||||
// otherwise redirect to the registration page.
|
||||
func (c *AuthController) logout() {
|
||||
func (c *AuthController) logout() mvc.Response {
|
||||
if c.isLoggedIn() {
|
||||
// c.Manager is the Sessions manager created
|
||||
// by the embedded SessionController, automatically.
|
||||
c.Manager.DestroyByID(c.Session.ID())
|
||||
return
|
||||
c.Session.Destroy()
|
||||
}
|
||||
|
||||
c.Path = PathLogin
|
||||
}
|
||||
|
||||
// AllowUser will check if this client is a logged user,
|
||||
// if not then it will redirect that guest to the login page
|
||||
// otherwise it will allow the execution of the next handler.
|
||||
func AllowUser(ctx iris.Context) {
|
||||
if ctx.Values().Get(sessionIDKey) != nil {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
ctx.Redirect(PathLogin)
|
||||
return PathLogin
|
||||
}
|
||||
|
|
|
@ -1,8 +1,18 @@
|
|||
package user
|
||||
|
||||
const (
|
||||
pathMyProfile = "/user/me"
|
||||
pathRegister = "/user/register"
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
)
|
||||
|
||||
var (
|
||||
// About Code: iris.StatusSeeOther ->
|
||||
// When redirecting from POST to GET request you -should- use this HTTP status code,
|
||||
// however there're some (complicated) alternatives if you
|
||||
// search online or even the HTTP RFC.
|
||||
// "See Other" RFC 7231
|
||||
pathMyProfile = mvc.Response{Path: "/user/me", Code: iris.StatusSeeOther}
|
||||
pathRegister = mvc.Response{Path: "/user/register"}
|
||||
)
|
||||
|
||||
// Controller is responsible to handle the following requests:
|
||||
|
@ -17,71 +27,89 @@ type Controller struct {
|
|||
AuthController
|
||||
}
|
||||
|
||||
type formValue func(string) string
|
||||
|
||||
// BeforeActivation called once before the server start
|
||||
// and before the controller's registration, here you can add
|
||||
// dependencies, to this controller and only, that the main caller may skip.
|
||||
func (c *Controller) BeforeActivation(b mvc.BeforeActivation) {
|
||||
// bind the context's `FormValue` as well in order to be
|
||||
// acceptable on the controller or its methods' input arguments (NEW feature as well).
|
||||
b.Dependencies().Add(func(ctx iris.Context) formValue { return ctx.FormValue })
|
||||
}
|
||||
|
||||
type page struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
// GetRegister handles GET:/user/register.
|
||||
func (c *Controller) GetRegister() {
|
||||
// mvc.Result can accept any struct which contains a `Dispatch(ctx iris.Context)` method.
|
||||
// Both mvc.Response and mvc.View are mvc.Result.
|
||||
func (c *Controller) GetRegister() mvc.Result {
|
||||
if c.isLoggedIn() {
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
|
||||
c.Data["Title"] = "User Registration"
|
||||
c.Tmpl = pathRegister + ".html"
|
||||
// You could just use it as a variable to win some time in serve-time,
|
||||
// this is an exersise for you :)
|
||||
return mvc.View{
|
||||
Name: pathRegister.Path + ".html",
|
||||
Data: page{"User Registration"},
|
||||
}
|
||||
}
|
||||
|
||||
// PostRegister handles POST:/user/register.
|
||||
func (c *Controller) PostRegister() {
|
||||
func (c *Controller) PostRegister(form formValue) mvc.Result {
|
||||
// we can either use the `c.Ctx.ReadForm` or read values one by one.
|
||||
var (
|
||||
firstname = c.Ctx.FormValue("firstname")
|
||||
username = c.Ctx.FormValue("username")
|
||||
password = c.Ctx.FormValue("password")
|
||||
firstname = form("firstname")
|
||||
username = form("username")
|
||||
password = form("password")
|
||||
)
|
||||
|
||||
user, err := c.createOrUpdate(firstname, username, password)
|
||||
if err != nil {
|
||||
c.fireError(err)
|
||||
return
|
||||
return c.fireError(err)
|
||||
}
|
||||
|
||||
// setting a session value was never easier.
|
||||
c.Session.Set(sessionIDKey, user.ID)
|
||||
// succeed, nothing more to do here, just redirect to the /user/me.
|
||||
return pathMyProfile
|
||||
}
|
||||
|
||||
// When redirecting from POST to GET request you -should- use this HTTP status code,
|
||||
// however there're some (complicated) alternatives if you
|
||||
// search online or even the HTTP RFC.
|
||||
c.Status = 303 // "See Other" RFC 7231
|
||||
|
||||
// Redirect to GET: /user/me
|
||||
// by changing the Path (and the status code because we're in POST request at this case).
|
||||
c.Path = pathMyProfile
|
||||
// with these static views,
|
||||
// you can use variables-- that are initialized before server start
|
||||
// so you can win some time on serving.
|
||||
// You can do it else where as well but I let them as pracise for you,
|
||||
// essentialy you can understand by just looking below.
|
||||
var userLoginView = mvc.View{
|
||||
Name: PathLogin.Path + ".html",
|
||||
Data: page{"User Login"},
|
||||
}
|
||||
|
||||
// GetLogin handles GET:/user/login.
|
||||
func (c *Controller) GetLogin() {
|
||||
func (c *Controller) GetLogin() mvc.Result {
|
||||
if c.isLoggedIn() {
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
c.Data["Title"] = "User Login"
|
||||
c.Tmpl = PathLogin + ".html"
|
||||
return userLoginView
|
||||
}
|
||||
|
||||
// PostLogin handles POST:/user/login.
|
||||
func (c *Controller) PostLogin() {
|
||||
func (c *Controller) PostLogin(form formValue) mvc.Result {
|
||||
var (
|
||||
username = c.Ctx.FormValue("username")
|
||||
password = c.Ctx.FormValue("password")
|
||||
username = form("username")
|
||||
password = form("password")
|
||||
)
|
||||
|
||||
user, err := c.verify(username, password)
|
||||
if err != nil {
|
||||
c.fireError(err)
|
||||
return
|
||||
return c.fireError(err)
|
||||
}
|
||||
|
||||
c.Session.Set(sessionIDKey, user.ID)
|
||||
c.Path = pathMyProfile
|
||||
return pathMyProfile
|
||||
}
|
||||
|
||||
// AnyLogout handles any method on path /user/logout.
|
||||
|
@ -90,44 +118,72 @@ func (c *Controller) AnyLogout() {
|
|||
}
|
||||
|
||||
// GetMe handles GET:/user/me.
|
||||
func (c *Controller) GetMe() {
|
||||
func (c *Controller) GetMe() mvc.Result {
|
||||
id, err := c.Session.GetInt64(sessionIDKey)
|
||||
if err != nil || id <= 0 {
|
||||
// when not already logged in.
|
||||
c.Path = PathLogin
|
||||
return
|
||||
// when not already logged in, redirect to login.
|
||||
return PathLogin
|
||||
}
|
||||
|
||||
u, found := c.Source.GetByID(id)
|
||||
if !found {
|
||||
// if the session exists but for some reason the user doesn't exist in the "database"
|
||||
// then logout him and redirect to the register page.
|
||||
c.logout()
|
||||
return
|
||||
return c.logout()
|
||||
}
|
||||
|
||||
// set the model and render the view template.
|
||||
c.User = u
|
||||
c.Data["Title"] = "Profile of " + u.Username
|
||||
c.Tmpl = pathMyProfile + ".html"
|
||||
return mvc.View{
|
||||
Name: pathMyProfile.Path + ".html",
|
||||
Data: iris.Map{
|
||||
"Title": "Profile of " + u.Username,
|
||||
"User": u,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) renderNotFound(id int64) {
|
||||
c.Status = 404
|
||||
c.Data["Title"] = "User Not Found"
|
||||
c.Data["ID"] = id
|
||||
c.Tmpl = "user/notfound.html"
|
||||
func (c *Controller) renderNotFound(id int64) mvc.View {
|
||||
return mvc.View{
|
||||
Code: iris.StatusNotFound,
|
||||
Name: "user/notfound.html",
|
||||
Data: iris.Map{
|
||||
"Title": "User Not Found",
|
||||
"ID": id,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Dispatch completes the `mvc.Result` interface
|
||||
// in order to be able to return a type of `Model`
|
||||
// as mvc.Result.
|
||||
// If this function didn't exist then
|
||||
// we should explicit set the output result to that Model or to an interface{}.
|
||||
func (u Model) Dispatch(ctx iris.Context) {
|
||||
ctx.JSON(u)
|
||||
}
|
||||
|
||||
// GetBy handles GET:/user/{id:long},
|
||||
// i.e http://localhost:8080/user/1
|
||||
func (c *Controller) GetBy(userID int64) {
|
||||
func (c *Controller) GetBy(userID int64) mvc.Result {
|
||||
// we have /user/{id}
|
||||
// fetch and render user json.
|
||||
if user, found := c.Source.GetByID(userID); !found {
|
||||
user, found := c.Source.GetByID(userID)
|
||||
if !found {
|
||||
// not user found with that ID.
|
||||
c.renderNotFound(userID)
|
||||
} else {
|
||||
c.Ctx.JSON(user)
|
||||
return c.renderNotFound(userID)
|
||||
}
|
||||
|
||||
// Q: how the hell Model can be return as mvc.Result?
|
||||
// A: I told you before on some comments and the docs,
|
||||
// any struct that has a `Dispatch(ctx iris.Context)`
|
||||
// can be returned as an mvc.Result(see ~20 lines above),
|
||||
// therefore we are able to combine many type of results in the same method.
|
||||
// For example, here, we return either an mvc.View to render a not found custom template
|
||||
// either a user which returns the Model as JSON via its Dispatch.
|
||||
//
|
||||
// We could also return just a struct value that is not an mvc.Result,
|
||||
// if the output result of the `GetBy` was that struct's type or an interface{}
|
||||
// and iris would render that with JSON as well, but here we can't do that without complete the `Dispatch`
|
||||
// function, because we may return an mvc.View which is an mvc.Result.
|
||||
return user
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@ -10,7 +11,7 @@ func main() {
|
|||
templates := iris.HTML("./views", ".html").Layout("shared/layout.html")
|
||||
app.RegisterView(templates)
|
||||
|
||||
app.Controller("/", new(Controller))
|
||||
mvc.New(app).Register(new(Controller))
|
||||
|
||||
// http://localhost:9091
|
||||
app.Run(iris.Addr(":9091"))
|
||||
|
@ -21,22 +22,28 @@ type Layout struct {
|
|||
Title string
|
||||
}
|
||||
|
||||
// Controller is our example controller.
|
||||
// Controller is our example controller, request-scoped, each request has its own instance.
|
||||
type Controller struct {
|
||||
iris.Controller
|
||||
|
||||
Layout Layout `iris:"model"`
|
||||
Layout Layout
|
||||
}
|
||||
|
||||
// BeginRequest is the first method fires when client requests from this Controller's path.
|
||||
// BeginRequest is the first method fired when client requests from this Controller's root path.
|
||||
func (c *Controller) BeginRequest(ctx iris.Context) {
|
||||
c.Controller.BeginRequest(ctx)
|
||||
|
||||
c.Layout.Title = "Home Page"
|
||||
}
|
||||
|
||||
// EndRequest is the last method fired.
|
||||
// It's here just to complete the BaseController
|
||||
// in order to be tell iris to call the `BeginRequest` before the main method.
|
||||
func (c *Controller) EndRequest(ctx iris.Context) {}
|
||||
|
||||
// Get handles GET http://localhost:9091
|
||||
func (c *Controller) Get() {
|
||||
c.Tmpl = "index.html"
|
||||
c.Data["Message"] = "Welcome to my website!"
|
||||
func (c *Controller) Get() mvc.View {
|
||||
return mvc.View{
|
||||
Name: "index.html",
|
||||
Data: iris.Map{
|
||||
"Layout": c.Layout,
|
||||
"Message": "Welcome to my website!",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,13 +2,18 @@ package main
|
|||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
type postValue func(string) string
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Controller("/user", new(UserController))
|
||||
mvc.New(app.Party("/user")).AddDependencies(
|
||||
func(ctx iris.Context) postValue {
|
||||
return ctx.PostValue
|
||||
}).Register(new(UserController))
|
||||
|
||||
// GET http://localhost:9092/user
|
||||
// GET http://localhost:9092/user/42
|
||||
|
@ -20,37 +25,44 @@ func main() {
|
|||
}
|
||||
|
||||
// UserController is our user example controller.
|
||||
type UserController struct {
|
||||
iris.Controller
|
||||
}
|
||||
type UserController struct{}
|
||||
|
||||
// Get handles GET /user
|
||||
func (c *UserController) Get() {
|
||||
c.Ctx.Writef("Select all users")
|
||||
func (c *UserController) Get() string {
|
||||
return "Select all users"
|
||||
}
|
||||
|
||||
// GetBy handles GET /user/42
|
||||
func (c *UserController) GetBy(id int) {
|
||||
c.Ctx.Writef("Select user by ID: %d", id)
|
||||
// User is our test User model, nothing tremendous here.
|
||||
type User struct{ ID int64 }
|
||||
|
||||
// GetBy handles GET /user/42, equal to .Get("/user/{id:long}")
|
||||
func (c *UserController) GetBy(id int64) User {
|
||||
// Select User by ID == $id.
|
||||
return User{id}
|
||||
}
|
||||
|
||||
// Post handles POST /user
|
||||
func (c *UserController) Post() {
|
||||
username := c.Ctx.PostValue("username")
|
||||
c.Ctx.Writef("Create by user with username: %s", username)
|
||||
func (c *UserController) Post(post postValue) string {
|
||||
username := post("username")
|
||||
return "Create by user with username: " + username
|
||||
}
|
||||
|
||||
// PutBy handles PUT /user/42
|
||||
func (c *UserController) PutBy(id int) {
|
||||
c.Ctx.Writef("Update user by ID: %d", id)
|
||||
func (c *UserController) PutBy(id int) string {
|
||||
// Update user by ID == $id
|
||||
return "User updated"
|
||||
}
|
||||
|
||||
// DeleteBy handles DELETE /user/42
|
||||
func (c *UserController) DeleteBy(id int) {
|
||||
c.Ctx.Writef("Delete user by ID: %d", id)
|
||||
func (c *UserController) DeleteBy(id int) bool {
|
||||
// Delete user by ID == %id
|
||||
//
|
||||
// when boolean then true = iris.StatusOK, false = iris.StatusNotFound
|
||||
return true
|
||||
}
|
||||
|
||||
// GetFollowersBy handles GET /user/followers/42
|
||||
func (c *UserController) GetFollowersBy(id int) {
|
||||
c.Ctx.Writef("Select all followers by user ID: %d", id)
|
||||
func (c *UserController) GetFollowersBy(id int) []User {
|
||||
// Select all followers by user ID == $id
|
||||
return []User{ /* ... */ }
|
||||
}
|
||||
|
|
|
@ -17,13 +17,13 @@ type TodoController struct {
|
|||
}
|
||||
|
||||
// BeforeActivation called once before the server ran, and before
|
||||
// the routes and dependency binder builded.
|
||||
// the routes and dependencies binded.
|
||||
// You can bind custom things to the controller, add new methods, add middleware,
|
||||
// add dependencies to the struct or the method(s) and more.
|
||||
func (c *TodoController) BeforeActivation(ca *mvc.ControllerActivator) {
|
||||
func (c *TodoController) BeforeActivation(b mvc.BeforeActivation) {
|
||||
// this could be binded to a controller's function input argument
|
||||
// if any, or struct field if any:
|
||||
ca.Dependencies.Add(func(ctx iris.Context) todo.Item {
|
||||
b.Dependencies().Add(func(ctx iris.Context) todo.Item {
|
||||
// ctx.ReadForm(&item)
|
||||
var (
|
||||
owner = ctx.PostValue("owner")
|
||||
|
|
54
deprecated.go
Normal file
54
deprecated.go
Normal file
|
@ -0,0 +1,54 @@
|
|||
package iris
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/kataras/iris/core/router"
|
||||
"github.com/kataras/iris/mvc"
|
||||
)
|
||||
|
||||
// Controller method is DEPRECATED, use the "mvc" subpackage instead, i.e
|
||||
// import "github.com/kataras/iris/mvc" and read its docs among with its new features at:
|
||||
// https://github.com/kataras/iris/blob/master/HISTORY.md#mo-01-jenuary-2018--v10
|
||||
func (app *Application) Controller(relPath string, c interface{}, _ ...interface{}) []*router.Route {
|
||||
name := mvc.NameOf(c)
|
||||
panic(fmt.Errorf(`"Controller" method is DEPRECATED, use the "mvc" subpackage instead.
|
||||
|
||||
PREVIOUSLY YOU USED TO CODE IT LIKE THIS:
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
// ...
|
||||
)
|
||||
|
||||
app.Controller("%s", new(%s), Struct_Values_Binded_To_The_Fields_Or_And_Any_Middleware)
|
||||
|
||||
NOW YOU SHOULD CODE IT LIKE THIS:
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/mvc"
|
||||
// ...
|
||||
)
|
||||
|
||||
// or use it like this: ).AddDependencies(...).Register(new(%s))
|
||||
mvc.Configure(app.Party("%s"), myMVC)
|
||||
|
||||
func myMVC(mvcApp *mvc.Application) {
|
||||
mvcApp.AddDependencies(
|
||||
Struct_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods,
|
||||
Or_And_Func_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods,
|
||||
)
|
||||
|
||||
mvcApp.Router.Use(Any_Middleware)
|
||||
|
||||
mvcApp.Register(new(%s))
|
||||
}
|
||||
|
||||
The new MVC implementation contains a lot more than the above,
|
||||
this is the reason you see more lines for a simple controller.
|
||||
|
||||
Please read more about the newest, amazing, features by navigating below
|
||||
https://github.com/kataras/iris/blob/master/HISTORY.md#mo-01-jenuary-2018--v1000`, // v10.0.0, we skip the number 9.
|
||||
relPath, name, name, relPath, name))
|
||||
}
|
|
@ -24,7 +24,7 @@ type BaseController interface {
|
|||
type shared interface {
|
||||
Name() string
|
||||
Router() router.Party
|
||||
Handle(method, path, funcName string, middleware ...context.Handler) *router.Route
|
||||
Handle(httpMethod, path, funcName string, middleware ...context.Handler) *router.Route
|
||||
}
|
||||
|
||||
type BeforeActivation interface {
|
||||
|
@ -34,7 +34,7 @@ type BeforeActivation interface {
|
|||
|
||||
type AfterActivation interface {
|
||||
shared
|
||||
DependenciesReadOnly() di.ValuesReadOnly
|
||||
DependenciesReadOnly() ValuesReadOnly
|
||||
Singleton() bool
|
||||
}
|
||||
|
||||
|
@ -66,12 +66,12 @@ type ControllerActivator struct {
|
|||
// on incoming requests.
|
||||
dependencies di.Values
|
||||
|
||||
// on activate.
|
||||
// initialized on the first `Handle`.
|
||||
injector *di.StructInjector
|
||||
}
|
||||
|
||||
func getNameOf(typ reflect.Type) string {
|
||||
elemTyp := di.IndirectType(typ)
|
||||
func NameOf(v interface{}) string {
|
||||
elemTyp := di.IndirectType(di.ValueOf(v).Type())
|
||||
|
||||
typName := elemTyp.Name()
|
||||
pkgPath := elemTyp.PkgPath()
|
||||
|
@ -80,22 +80,17 @@ func getNameOf(typ reflect.Type) string {
|
|||
return fullname
|
||||
}
|
||||
|
||||
func newControllerActivator(router router.Party, controller interface{}, dependencies di.Values) *ControllerActivator {
|
||||
var (
|
||||
val = reflect.ValueOf(controller)
|
||||
typ = val.Type()
|
||||
|
||||
// the full name of the controller: its type including the package path.
|
||||
fullName = getNameOf(typ)
|
||||
)
|
||||
func newControllerActivator(router router.Party, controller interface{}, dependencies []reflect.Value) *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,
|
||||
Value: val,
|
||||
Type: typ,
|
||||
fullName: fullName,
|
||||
router: router,
|
||||
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
|
||||
// to register a route via the `Handle`,
|
||||
// all available exported and compatible methods
|
||||
|
@ -106,7 +101,8 @@ func newControllerActivator(router router.Party, controller interface{}, depende
|
|||
// TODO: now that BaseController is totally optionally
|
||||
// we have to check if BeginRequest and EndRequest should be here.
|
||||
reservedMethods: whatReservedMethods(typ),
|
||||
dependencies: dependencies,
|
||||
// CloneWithFieldsOf: include the manual fill-ed controller struct's fields to the dependencies.
|
||||
dependencies: di.Values(dependencies).CloneWithFieldsOf(controller),
|
||||
}
|
||||
|
||||
return c
|
||||
|
@ -125,7 +121,20 @@ func (c *ControllerActivator) Dependencies() *di.Values {
|
|||
return &c.dependencies
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) DependenciesReadOnly() di.ValuesReadOnly {
|
||||
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
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) DependenciesReadOnly() ValuesReadOnly {
|
||||
return c.dependencies
|
||||
}
|
||||
|
||||
|
@ -144,9 +153,9 @@ func (c *ControllerActivator) Router() router.Party {
|
|||
// any unexported fields and all fields are services-like, static.
|
||||
func (c *ControllerActivator) Singleton() bool {
|
||||
if c.injector == nil {
|
||||
panic("MVC: IsRequestScoped used on an invalid state the API gives access to it only `AfterActivation`, report this as bug")
|
||||
panic("MVC: Singleton used on an invalid state the API gives access to it only `AfterActivation`, report this as bug")
|
||||
}
|
||||
return c.injector.State == di.Singleton
|
||||
return c.injector.Scope == di.Singleton
|
||||
}
|
||||
|
||||
// checks if a method is already registered.
|
||||
|
@ -160,18 +169,12 @@ func (c *ControllerActivator) isReservedMethod(name string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) parseMethod(m reflect.Method) {
|
||||
httpMethod, httpPath, err := parseMethod(m, c.isReservedMethod)
|
||||
if err != nil {
|
||||
if err != errSkip {
|
||||
err = fmt.Errorf("MVC: fail to parse the route path and HTTP method for '%s.%s': %v", c.fullName, m.Name, err)
|
||||
c.router.GetReporter().AddErr(err)
|
||||
func (c *ControllerActivator) activate() {
|
||||
c.parseMethods()
|
||||
}
|
||||
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.Handle(httpMethod, httpPath, m.Name)
|
||||
func (c *ControllerActivator) addErr(err error) bool {
|
||||
return c.router.GetReporter().AddErr(err)
|
||||
}
|
||||
|
||||
// register all available, exported methods to handlers if possible.
|
||||
|
@ -183,8 +186,17 @@ func (c *ControllerActivator) parseMethods() {
|
|||
}
|
||||
}
|
||||
|
||||
func (c *ControllerActivator) activate() {
|
||||
c.parseMethods()
|
||||
func (c *ControllerActivator) parseMethod(m reflect.Method) {
|
||||
httpMethod, httpPath, err := parseMethod(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))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
c.Handle(httpMethod, httpPath, m.Name)
|
||||
}
|
||||
|
||||
// Handle registers a route based on a http method, the route's path
|
||||
|
@ -202,44 +214,18 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware .
|
|||
return nil
|
||||
}
|
||||
|
||||
// Remember:
|
||||
// we cannot simply do that and expect to work:
|
||||
// hasStructInjector = c.injector != nil && c.injector.Valid
|
||||
// hasFuncInjector = funcInjector != nil && funcInjector.Valid
|
||||
// because
|
||||
// the `Handle` can be called from `BeforeActivation` callbacks
|
||||
// and before activation, the c.injector is nil because
|
||||
// we may not have the dependencies binded yet. But if `c.injector.Valid`
|
||||
// inside the Handelr works because it's set on the `activate()` method.
|
||||
// To solve this we can make check on the FIRST `Handle`,
|
||||
// if c.injector is nil, then set it with the current bindings,
|
||||
// so the user should bind the dependencies needed before the `Handle`
|
||||
// this is a logical flow, so we will choose that one ->
|
||||
if c.injector == nil {
|
||||
// first, set these bindings to the passed controller, they will be useless
|
||||
// if the struct contains any dynamic value because this controller will
|
||||
// be never fired as it's but we make that in order to get the length of the static
|
||||
// matched dependencies of the struct.
|
||||
c.injector = di.MakeStructInjector(c.Value, hijacker, typeChecker, c.dependencies...)
|
||||
if c.injector.HasFields {
|
||||
golog.Debugf("MVC dependencies of '%s':\n%s", c.fullName, c.injector.String())
|
||||
}
|
||||
}
|
||||
|
||||
// get the method from the controller type.
|
||||
m, ok := c.Type.MethodByName(funcName)
|
||||
if !ok {
|
||||
err := fmt.Errorf("MVC: function '%s' doesn't exist inside the '%s' controller",
|
||||
funcName, c.fullName)
|
||||
c.router.GetReporter().AddErr(err)
|
||||
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.router.Macros())
|
||||
if err != nil {
|
||||
err = fmt.Errorf("MVC: fail to parse the path for '%s.%s': %v", c.fullName, funcName, err)
|
||||
c.router.GetReporter().AddErr(err)
|
||||
c.addErr(fmt.Errorf("MVC: fail to parse the path for '%s.%s': %v", c.fullName, funcName, err))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -257,23 +243,40 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware .
|
|||
|
||||
// register the handler now.
|
||||
route := c.router.Handle(method, path, append(middleware, handler)...)
|
||||
if route != nil {
|
||||
// change the main handler's name in order to respect the controller's and give
|
||||
// a proper debug message.
|
||||
route.MainHandlerName = fmt.Sprintf("%s.%s", c.fullName, funcName)
|
||||
|
||||
// add this as a reserved method name in order to
|
||||
// be sure that the same func will not be registered again,
|
||||
// even if a custom .Handle later on.
|
||||
c.reservedMethods = append(c.reservedMethods, funcName)
|
||||
if route == nil {
|
||||
c.addErr(fmt.Errorf("MVC: unable to register a route for the path for '%s.%s'", c.fullName, funcName))
|
||||
return nil
|
||||
}
|
||||
|
||||
// change the main handler's name in order to respect the controller's and give
|
||||
// a proper debug message.
|
||||
route.MainHandlerName = fmt.Sprintf("%s.%s", c.fullName, funcName)
|
||||
|
||||
// add this as a reserved method name in order to
|
||||
// be sure that the same func will not be registered again,
|
||||
// even if a custom .Handle later on.
|
||||
c.reservedMethods = append(c.reservedMethods, funcName)
|
||||
|
||||
return route
|
||||
}
|
||||
|
||||
var emptyIn = []reflect.Value{}
|
||||
|
||||
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 binded 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.
|
||||
if c.injector == nil {
|
||||
c.injector = di.MakeStructInjector(c.Value, hijacker, typeChecker, c.dependencies...)
|
||||
if c.injector.HasFields {
|
||||
golog.Debugf("MVC dependencies of '%s':\n%s", c.fullName, c.injector.String())
|
||||
}
|
||||
}
|
||||
|
||||
// fmt.Printf("for %s | values: %s\n", funcName, funcDependencies)
|
||||
funcInjector := di.MakeFuncInjector(m.Func, hijacker, typeChecker, funcDependencies...)
|
||||
// fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length)
|
||||
|
@ -291,14 +294,14 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref
|
|||
|
||||
if !implementsBase && !hasBindableFields && !hasBindableFuncInputs {
|
||||
return func(ctx context.Context) {
|
||||
DispatchFuncResult(ctx, call(c.injector.NewAsSlice()))
|
||||
DispatchFuncResult(ctx, call(c.injector.AcquireSlice()))
|
||||
}
|
||||
}
|
||||
|
||||
n := m.Type.NumIn()
|
||||
return func(ctx context.Context) {
|
||||
var (
|
||||
ctrl = c.injector.New()
|
||||
ctrl = c.injector.Acquire()
|
||||
ctxValue reflect.Value
|
||||
)
|
||||
|
||||
|
|
|
@ -486,8 +486,6 @@ func TestControllerNotCreateNewDueManuallySettingAllFields(t *testing.T) {
|
|||
TitlePointer: &testBindType{
|
||||
title: "my title",
|
||||
},
|
||||
}, func(b BeforeActivation) {
|
||||
|
||||
})
|
||||
|
||||
e := httptest.New(t, app)
|
||||
|
|
11
mvc/di/TODO.txt
Normal file
11
mvc/di/TODO.txt
Normal file
|
@ -0,0 +1,11 @@
|
|||
I can do one of the followings to this "di" folder when I finish the cleanup and document it a bit,
|
||||
although I'm sick I will try to finish it tomorrow.
|
||||
|
||||
End-users don't need this.
|
||||
1) So, rename this to "internal".
|
||||
|
||||
I don't know if something similar exist in Go,
|
||||
it's a dependency injection framework at the end, and a very fast one.
|
||||
|
||||
2) So I'm thinking to push it to a different repo,
|
||||
like https://github.com/kataras/di or even to my small common https://github.com/kataras/pkg collection.
|
11
mvc/di/di.go
11
mvc/di/di.go
|
@ -57,15 +57,14 @@ func (d *D) Clone() *D {
|
|||
// with the injector's `Inject` and `InjectElem` methods.
|
||||
func (d *D) Struct(s interface{}) *StructInjector {
|
||||
if s == nil {
|
||||
return nil
|
||||
return &StructInjector{HasFields: false}
|
||||
}
|
||||
v := ValueOf(s)
|
||||
|
||||
return MakeStructInjector(
|
||||
v,
|
||||
ValueOf(s),
|
||||
d.hijacker,
|
||||
d.goodFunc,
|
||||
d.Values...,
|
||||
d.Values.CloneWithFieldsOf(s)...,
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -75,6 +74,10 @@ func (d *D) Struct(s interface{}) *StructInjector {
|
|||
// to the function's input argument when called
|
||||
// with the injector's `Fill` method.
|
||||
func (d *D) Func(fn interface{}) *FuncInjector {
|
||||
if fn == nil {
|
||||
return &FuncInjector{Valid: false}
|
||||
}
|
||||
|
||||
return MakeFuncInjector(
|
||||
ValueOf(fn),
|
||||
d.hijacker,
|
||||
|
|
|
@ -5,10 +5,10 @@ import (
|
|||
"reflect"
|
||||
)
|
||||
|
||||
type State uint8
|
||||
type Scope uint8
|
||||
|
||||
const (
|
||||
Stateless State = iota
|
||||
Stateless Scope = iota
|
||||
Singleton
|
||||
)
|
||||
|
||||
|
@ -29,7 +29,7 @@ type (
|
|||
// see `setState`.
|
||||
HasFields bool
|
||||
CanInject bool // if any bindable fields when the state is NOT singleton.
|
||||
State State
|
||||
Scope Scope
|
||||
}
|
||||
)
|
||||
|
||||
|
@ -121,13 +121,13 @@ func (s *StructInjector) setState() {
|
|||
// if the number of static values binded is equal to the
|
||||
// total struct's fields(including unexported fields this time) then set as singleton.
|
||||
if staticBindingsFieldsLength == allStructFieldsLength {
|
||||
s.State = Singleton
|
||||
s.Scope = Singleton
|
||||
// the default is `Stateless`, which means that a new instance should be created
|
||||
// on each inject action by the caller.
|
||||
return
|
||||
}
|
||||
|
||||
s.CanInject = s.State == Stateless && s.HasFields
|
||||
s.CanInject = s.Scope == Stateless && s.HasFields
|
||||
}
|
||||
|
||||
// fill the static bindings values once.
|
||||
|
@ -177,15 +177,15 @@ func (s *StructInjector) InjectElem(destElem reflect.Value, ctx ...reflect.Value
|
|||
}
|
||||
}
|
||||
|
||||
func (s *StructInjector) New() reflect.Value {
|
||||
if s.State == Singleton {
|
||||
func (s *StructInjector) Acquire() reflect.Value {
|
||||
if s.Scope == Singleton {
|
||||
return s.initRef
|
||||
}
|
||||
return reflect.New(s.elemType)
|
||||
}
|
||||
|
||||
func (s *StructInjector) NewAsSlice() []reflect.Value {
|
||||
if s.State == Singleton {
|
||||
func (s *StructInjector) AcquireSlice() []reflect.Value {
|
||||
if s.Scope == Singleton {
|
||||
return s.initRefAsSlice
|
||||
}
|
||||
return []reflect.Value{reflect.New(s.elemType)}
|
||||
|
|
|
@ -2,16 +2,6 @@ package di
|
|||
|
||||
import "reflect"
|
||||
|
||||
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() Values
|
||||
}
|
||||
|
||||
type Values []reflect.Value
|
||||
|
||||
func NewValues() Values {
|
||||
|
@ -30,7 +20,7 @@ func (bv Values) Clone() Values {
|
|||
}
|
||||
|
||||
// CloneWithFieldsOf will return a copy of the current values
|
||||
// plus the "v" struct's fields that are filled(non-zero) by the caller.
|
||||
// plus the "s" struct's fields that are filled(non-zero) by the caller.
|
||||
func (bv Values) CloneWithFieldsOf(s interface{}) Values {
|
||||
values := bv.Clone()
|
||||
|
||||
|
|
|
@ -84,30 +84,24 @@ func (e *Engine) Handler(handler interface{}) context.Handler {
|
|||
// where Get is an HTTP Method func.
|
||||
//
|
||||
// Examples at: https://github.com/kataras/iris/tree/master/_examples/mvc.
|
||||
func (e *Engine) Controller(router router.Party, controller interface{}, beforeActivate ...func(BeforeActivation)) {
|
||||
// add the manual filled fields to the dependencies.
|
||||
dependencies := e.Dependencies.CloneWithFieldsOf(controller)
|
||||
ca := newControllerActivator(router, controller, dependencies)
|
||||
func (e *Engine) Controller(router router.Party, controller interface{}) {
|
||||
// initialize the controller's activator, nothing too magical so far.
|
||||
c := newControllerActivator(router, controller, e.Dependencies)
|
||||
|
||||
// give a priority to the "beforeActivate"
|
||||
// callbacks, if any.
|
||||
for _, cb := range beforeActivate {
|
||||
cb(ca)
|
||||
}
|
||||
|
||||
// check if controller has an "BeforeActivation" function
|
||||
// which accepts the controller activator and call it.
|
||||
if activateListener, ok := controller.(interface {
|
||||
// check the controller's "BeforeActivation" or/and "AfterActivation" method(s) between the `activate`
|
||||
// call, which is simply parses the controller's methods, end-dev can register custom controller's methods
|
||||
// by using the BeforeActivation's (a ControllerActivation) `.Handle` method.
|
||||
if before, ok := controller.(interface {
|
||||
BeforeActivation(BeforeActivation)
|
||||
}); ok {
|
||||
activateListener.BeforeActivation(ca)
|
||||
before.BeforeActivation(c)
|
||||
}
|
||||
|
||||
ca.activate()
|
||||
c.activate()
|
||||
|
||||
if afterActivateListener, ok := controller.(interface {
|
||||
if after, okAfter := controller.(interface {
|
||||
AfterActivation(AfterActivation)
|
||||
}); ok {
|
||||
afterActivateListener.AfterActivation(ca)
|
||||
}); okAfter {
|
||||
after.AfterActivation(c)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -264,9 +264,10 @@ func (t *testControllerViewResultRespectCtxViewData) Get() Result {
|
|||
|
||||
func TestControllerViewResultRespectCtxViewData(t *testing.T) {
|
||||
app := iris.New()
|
||||
NewEngine().Controller(app, new(testControllerViewResultRespectCtxViewData), func(b BeforeActivation) {
|
||||
b.Dependencies().Add(t)
|
||||
})
|
||||
m := NewEngine()
|
||||
m.Dependencies.Add(t)
|
||||
m.Controller(app.Party("/"), new(testControllerViewResultRespectCtxViewData))
|
||||
|
||||
e := httptest.New(t, app)
|
||||
|
||||
e.GET("/").Expect().Status(iris.StatusInternalServerError)
|
||||
|
|
|
@ -65,26 +65,23 @@ func MakeHandler(handler interface{}, bindValues ...reflect.Value) (context.Hand
|
|||
return h, nil
|
||||
}
|
||||
|
||||
s := di.MakeFuncInjector(fn, hijacker, typeChecker, bindValues...)
|
||||
if !s.Valid {
|
||||
funcInjector := di.MakeFuncInjector(fn, hijacker, typeChecker, bindValues...)
|
||||
if !funcInjector.Valid {
|
||||
pc := fn.Pointer()
|
||||
fpc := runtime.FuncForPC(pc)
|
||||
callerFileName, callerLineNumber := fpc.FileLine(pc)
|
||||
callerName := fpc.Name()
|
||||
|
||||
err := fmt.Errorf("input arguments length(%d) and valid binders length(%d) are not equal for typeof '%s' which is defined at %s:%d by %s",
|
||||
n, s.Length, fn.Type().String(), callerFileName, callerLineNumber, callerName)
|
||||
n, funcInjector.Length, fn.Type().String(), callerFileName, callerLineNumber, callerName)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
h := func(ctx context.Context) {
|
||||
in := make([]reflect.Value, n, n)
|
||||
|
||||
s.Inject(&in, reflect.ValueOf(ctx))
|
||||
if ctx.IsStopped() {
|
||||
return
|
||||
}
|
||||
DispatchFuncResult(ctx, fn.Call(in))
|
||||
// in := make([]reflect.Value, n, n)
|
||||
// funcInjector.Inject(&in, reflect.ValueOf(ctx))
|
||||
// DispatchFuncResult(ctx, fn.Call(in))
|
||||
DispatchFuncResult(ctx, funcInjector.Call(reflect.ValueOf(ctx)))
|
||||
}
|
||||
|
||||
return h, nil
|
||||
|
|
2
mvc/ideas/1/TODO.txt
Normal file
2
mvc/ideas/1/TODO.txt
Normal file
|
@ -0,0 +1,2 @@
|
|||
Remove the "ideas" folder or move this example somewhere in the _examples/mvc or even make a https://medium.com/@kataras
|
||||
small tutorial about Iris' new MVC implementation.
|
39
mvc/mvc.go
39
mvc/mvc.go
|
@ -34,6 +34,26 @@ func New(party router.Party) *Application {
|
|||
return newApp(NewEngine(), party)
|
||||
}
|
||||
|
||||
// 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 Configure(party router.Party, configurators ...func(*Application)) *Application {
|
||||
// Author's Notes->
|
||||
// About the Configure's comment: +5 space to be shown in equal width to the previous or after line.
|
||||
//
|
||||
// About the Configure's design choosen:
|
||||
// Yes, we could just have a `New(party, configurators...)`
|
||||
// but I think the `New()` and `Configure(configurators...)` API seems more native to programmers,
|
||||
// at least to me and the people I ask for their opinion between them.
|
||||
// Because the `New()` can actually return something that can be fully configured without its `Configure`,
|
||||
// its `Configure` is there just to design the apps better and help end-devs to split their code wisely.
|
||||
return New(party).Configure(configurators...)
|
||||
}
|
||||
|
||||
// Configure can be used to pass one or more functions that accept this
|
||||
// Application, use this to add dependencies and controller(s).
|
||||
//
|
||||
|
@ -52,9 +72,9 @@ func (app *Application) Configure(configurators ...func(*Application)) *Applicat
|
|||
// will be binded to the controller's field, if matching or to the
|
||||
// controller's methods, if matching.
|
||||
//
|
||||
// The dependencies can be changed per-controller as well via a `beforeActivate`
|
||||
// on the `Register` method or when the controller has the `BeforeActivation(b BeforeActivation)`
|
||||
// method defined.
|
||||
// These dependencies "values" can be changed per-controller as well,
|
||||
// via controller's `BeforeActivation` and `AfterActivation` methods,
|
||||
// look the `Register` method for more.
|
||||
//
|
||||
// It returns this Application.
|
||||
//
|
||||
|
@ -68,15 +88,16 @@ func (app *Application) AddDependencies(values ...interface{}) *Application {
|
|||
// It accept any custom struct which its functions will be transformed
|
||||
// to routes.
|
||||
//
|
||||
// The second, optional and variadic argument is the "beforeActive",
|
||||
// use that when you want to modify the controller before the activation
|
||||
// and registration to the main Iris Application.
|
||||
// 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 Application.
|
||||
// It returns this mvc Application.
|
||||
//
|
||||
// Example: `.Register(new(TodoController))`.
|
||||
func (app *Application) Register(controller interface{}, beforeActivate ...func(BeforeActivation)) *Application {
|
||||
app.Engine.Controller(app.Router, controller, beforeActivate...)
|
||||
func (app *Application) Register(controller interface{}) *Application {
|
||||
app.Engine.Controller(app.Router, controller)
|
||||
return app
|
||||
}
|
||||
|
||||
|
|
|
@ -50,7 +50,9 @@ func TestPathParamBinder(t *testing.T) {
|
|||
t.Fatalf("expected the param 'username' to be '%s' but got '%s'", expectedUsername, got)
|
||||
}
|
||||
|
||||
// test the non executed if param not found.
|
||||
/* this is useless, we don't need to check if ctx.Stopped
|
||||
inside bindings, this is middleware's job.
|
||||
// test the non executed if param not found -> this is already done in Iris if real context, so ignore it.
|
||||
executed = false
|
||||
got = ""
|
||||
|
||||
|
@ -63,4 +65,5 @@ func TestPathParamBinder(t *testing.T) {
|
|||
if executed {
|
||||
t.Fatalf("expected the handler to not be executed")
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
|
|
@ -10,6 +10,9 @@ var defaultSessionManager = sessions.New(sessions.Config{})
|
|||
// SessionController is a simple `Controller` implementation
|
||||
// which requires a binded session manager in order to give
|
||||
// direct access to the current client's session via its `Session` field.
|
||||
//
|
||||
// SessionController is deprecated please use the `mvc.Session(manager)` instead, it's more useful,
|
||||
// also *sessions.Session type can now `Destroy` itself without the need of the manager, embrace it.
|
||||
type SessionController struct {
|
||||
Manager *sessions.Sessions
|
||||
Session *sessions.Session
|
||||
|
|
Loading…
Reference in New Issue
Block a user