1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-29 15:57:09 +00:00

Update to 8.3.0 | MVC Models and Bindings and fix of #723 , read HISTORY.md

Former-commit-id: d8f66d8d370c583a288333df2a14c6ee2dc56466
This commit is contained in:
kataras
2017-08-18 17:09:18 +03:00
parent 398d1e816c
commit b96476d100
53 changed files with 12642 additions and 1046 deletions

View File

@@ -10,11 +10,12 @@ import (
"github.com/kataras/iris/context"
"github.com/kataras/iris/core/errors"
"github.com/kataras/iris/core/router/macro"
"github.com/kataras/iris/mvc/activator"
)
const (
// MethodNone is a Virtual method
// to store the "offline" routes
// to store the "offline" routes.
MethodNone = "NONE"
)
@@ -172,6 +173,36 @@ func (api *APIBuilder) Handle(method string, relativePath string, handlers ...co
return r
}
// HandleMany works like `Handle` but can receive more than one
// paths separated by spaces and returns always a slice of *Route instead of a single instance of Route.
//
// It's useful only if the same handler can handle more than one request paths,
// otherwise use `Party` which can handle many paths with different handlers and middlewares.
//
// Usage:
// app.HandleMany(iris.MethodGet, "/user /user/{id:int} /user/me", userHandler)
// At the other side, with `Handle` we've had to write:
// app.Handle(iris.MethodGet, "/user", userHandler)
// app.Handle(iris.MethodGet, "/user/{id:int}", userByIDHandler)
// app.Handle(iris.MethodGet, "/user/me", userMeHandler)
//
// This method is used behind the scenes at the `Controller` function
// in order to handle more than one paths for the same controller instance.
func (api *APIBuilder) HandleMany(method string, relativePath string, handlers ...context.Handler) (routes []*Route) {
trimmedPath := strings.Trim(relativePath, " ")
// at least slash
// a space
// at least one other slash for the next path
// app.Controller("/user /user{id}", new(UserController))
paths := strings.Split(trimmedPath, " ")
for _, p := range paths {
if p != "" {
routes = append(routes, api.Handle(method, p, handlers...))
}
}
return
}
// Party is just a group joiner of routes which have the same prefix and share same middleware(s) also.
// Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun.
func (api *APIBuilder) Party(relativePath string, handlers ...context.Handler) Party {
@@ -400,15 +431,13 @@ func (api *APIBuilder) Trace(relativePath string, handlers ...context.Handler) *
// Any registers a route for ALL of the http methods
// (Get,Post,Put,Head,Patch,Options,Connect,Delete).
func (api *APIBuilder) Any(relativePath string, handlers ...context.Handler) []*Route {
routes := make([]*Route, len(AllMethods), len(AllMethods))
for i, k := range AllMethods {
r := api.Handle(k, relativePath, handlers...)
routes[i] = r
func (api *APIBuilder) Any(relativePath string, handlers ...context.Handler) (routes []*Route) {
for _, m := range AllMethods {
r := api.HandleMany(m, relativePath, handlers...)
routes = append(routes, r...)
}
return routes
return
}
// Controller registers a `Controller` instance and returns the registered Routes.
@@ -418,11 +447,15 @@ func (api *APIBuilder) Any(relativePath string, handlers ...context.Handler) []*
// It's just an alternative way of building an API for a specific
// path, the controller can register all type of http methods.
//
// Keep note that this method is a bit slow
// Keep note that controllers are bit slow
// because of the reflection use however it's as fast as possible because
// it does preparation before the serve-time handler but still
// remains slower than the low-level handlers
// such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch` .
// such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch`.
//
//
// All fields that are tagged with iris:"persistence"` or binded
// are being persistence and kept the same between the different requests.
//
// An Example Controller can be:
//
@@ -439,38 +472,53 @@ func (api *APIBuilder) Any(relativePath string, handlers ...context.Handler) []*
// Usage: app.Controller("/", new(IndexController))
//
//
// Another example with persistence data:
// Another example with bind:
//
// type UserController struct {
// Controller
//
// CreatedAt time.Time `iris:"persistence"`
// Title string `iris:"persistence"`
// DB *DB `iris:"persistence"`
// DB *DB
// CreatedAt time.Time
//
// }
//
// // Get serves using the User controller when HTTP Method is "GET".
// func (c *UserController) Get() {
// c.Tmpl = "user/index.html"
// c.Data["title"] = c.Title
// c.Data["title"] = "User Page"
// c.Data["username"] = "kataras " + c.Params.Get("userid")
// c.Data["connstring"] = c.DB.Connstring
// c.Data["uptime"] = time.Now().Sub(c.CreatedAt).Seconds()
// }
//
// Usage: app.Controller("/user/{id:int}", &UserController{
// CreatedAt: time.Now(),
// Title: "User page",
// DB: yourDB,
// })
// Usage: app.Controller("/user/{id:int}", new(UserController), db, time.Now())
//
// Read more at `router#Controller`.
func (api *APIBuilder) Controller(relativePath string, controller interface{}) []*Route {
routes, err := registerController(api, relativePath, controller)
// Read more at `/mvc#Controller`.
func (api *APIBuilder) Controller(relativePath string, controller activator.BaseController,
bindValues ...interface{}) (routes []*Route) {
registerFunc := func(method string, handler context.Handler) {
if method == "ANY" || method == "ALL" {
routes = api.Any(relativePath, handler)
} else {
routes = append(routes, api.HandleMany(method, relativePath, handler)...)
}
}
// bind any values to the controller's relative fields
// and set them on each new request controller,
// binder is an alternative method
// of the persistence data control which requires the
// user already set the values manually to controller's fields
// and tag them with `iris:"persistence"`.
//
// don't worry it will never be handled if empty values.
err := activator.Register(controller, bindValues, nil, registerFunc)
if err != nil {
api.reporter.Add("%v for path: '%s'", err, relativePath)
}
return routes
return
}
// StaticCacheDuration expiration duration for INACTIVE file handlers, it's the only one global configuration

View File

@@ -1,290 +0,0 @@
package router
import (
"reflect"
"strings"
"github.com/kataras/iris/context"
"github.com/kataras/iris/core/errors"
)
// Controller is the base controller for the high level controllers instances.
//
// This base controller is used as an alternative way of building
// APIs, the controller can register all type of http methods.
//
// Keep note that controllers are bit slow
// because of the reflection use however it's as fast as possible because
// it does preparation before the serve-time handler but still
// remains slower than the low-level handlers
// such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch`.
//
//
// All fields that are tagged with iris:"persistence"`
// are being persistence and kept between the different requests,
// meaning that these data will not be reset-ed on each new request,
// they will be the same for all requests.
//
// An Example Controller can be:
//
// type IndexController struct {
// Controller
// }
//
// func (c *IndexController) Get() {
// c.Tmpl = "index.html"
// c.Data["title"] = "Index page"
// c.Data["message"] = "Hello world!"
// }
//
// Usage: app.Controller("/", new(IndexController))
//
//
// Another example with persistence data:
//
// type UserController struct {
// Controller
//
// CreatedAt time.Time `iris:"persistence"`
// Title string `iris:"persistence"`
// DB *DB `iris:"persistence"`
// }
//
// // Get serves using the User controller when HTTP Method is "GET".
// func (c *UserController) Get() {
// c.Tmpl = "user/index.html"
// c.Data["title"] = c.Title
// c.Data["username"] = "kataras " + c.Params.Get("userid")
// c.Data["connstring"] = c.DB.Connstring
// c.Data["uptime"] = time.Now().Sub(c.CreatedAt).Seconds()
// }
//
// Usage: app.Controller("/user/{id:int}", &UserController{
// CreatedAt: time.Now(),
// Title: "User page",
// DB: yourDB,
// })
//
// Look `router#APIBuilder#Controller` method too.
type Controller struct {
// path params.
Params *context.RequestParams
// view properties.
Layout string
Tmpl string
Data map[string]interface{}
// give access to the request context itself.
Ctx context.Context
}
// all lowercase, so user can see only the fields
// that are necessary to him/her, do not confuse that
// with the optional custom `Init` of the higher-level Controller.
func (b *Controller) init(ctx context.Context) {
b.Ctx = ctx
b.Params = ctx.Params()
b.Data = make(map[string]interface{}, 0)
}
func (b *Controller) exec() {
if v := b.Tmpl; v != "" {
if l := b.Layout; l != "" {
b.Ctx.ViewLayout(l)
}
if d := b.Data; d != nil {
for key, value := range d {
b.Ctx.ViewData(key, value)
}
}
b.Ctx.View(v)
}
}
var (
// ErrInvalidControllerType is a static error which fired from `Controller` when
// the passed "c" instnace is not a valid type of `Controller`.
ErrInvalidControllerType = errors.New("controller should have a field of Controller type")
)
// get the field name at compile-time,
// will help us to catch any unexpected results on future versions.
var baseControllerName = reflect.TypeOf(Controller{}).Name()
// registers a controller to a specific `Party`.
// Consumed by `APIBuilder#Controller` function.
func registerController(p Party, path string, c interface{}) ([]*Route, error) {
typ := reflect.TypeOf(c)
if typ.Kind() != reflect.Ptr {
typ = reflect.PtrTo(typ)
}
elem := typ.Elem()
// check if "c" has the "Controller" typeof `Controller` field.
b, has := elem.FieldByName(baseControllerName)
if !has {
return nil, ErrInvalidControllerType
}
baseControllerFieldIndex := b.Index[0]
persistenceFields := make(map[int]reflect.Value, 0)
if numField := elem.NumField(); numField > 1 {
val := reflect.Indirect(reflect.ValueOf(c))
for i := 0; i < numField; i++ {
f := elem.Field(i)
valF := val.Field(i)
// catch persistence data by tags, i.e:
// MyData string `iris:"persistence"`
if t, ok := f.Tag.Lookup("iris"); ok {
if t == "persistence" {
persistenceFields[i] = reflect.ValueOf(valF.Interface())
continue
}
}
// no: , lets have only the tag
// even for pointers, this will make
// things clear
// so a *Session can be declared
// without having to introduce
// a new tag such as `iris:"omit_persistence"`
// old:
// catch persistence data by pointer, i.e:
// DB *Database
// if f.Type.Kind() == reflect.Ptr {
// if !valF.IsNil() {
// persistenceFields[i] = reflect.ValueOf(valF.Interface())
// }
// }
}
}
customInitFuncIndex, _ := getCustomFuncIndex(typ, customInitFuncNames...)
customEndFuncIndex, _ := getCustomFuncIndex(typ, customEndFuncNames...)
// check if has Any() or All()
// if yes, then register all http methods and
// exit.
m, has := typ.MethodByName("Any")
if !has {
m, has = typ.MethodByName("All")
}
if has {
routes := p.Any(path,
controllerToHandler(elem, persistenceFields,
baseControllerFieldIndex, m.Index, customInitFuncIndex, customEndFuncIndex))
return routes, nil
}
var routes []*Route
// else search the entire controller
// for any compatible method function
// and register that.
for _, method := range AllMethods {
httpMethodFuncName := strings.Title(strings.ToLower(method))
m, has := typ.MethodByName(httpMethodFuncName)
if !has {
continue
}
httpMethodIndex := m.Index
r := p.Handle(method, path,
controllerToHandler(elem, persistenceFields,
baseControllerFieldIndex, httpMethodIndex, customInitFuncIndex, customEndFuncIndex))
routes = append(routes, r)
}
return routes, nil
}
func controllerToHandler(elem reflect.Type, persistenceFields map[int]reflect.Value,
baseControllerFieldIndex, httpMethodIndex, customInitFuncIndex, customEndFuncIndex int) context.Handler {
return func(ctx context.Context) {
// create a new controller instance of that type(>ptr).
c := reflect.New(elem)
// get the responsible method.
// Remember:
// To improve the performance
// we don't compare the ctx.Method()[HTTP Method]
// to the instance's Method, each handler is registered
// to a specific http method.
methodFunc := c.Method(httpMethodIndex)
// get the Controller embedded field.
b, _ := c.Elem().Field(baseControllerFieldIndex).Addr().Interface().(*Controller)
if len(persistenceFields) > 0 {
elem := c.Elem()
for index, value := range persistenceFields {
elem.Field(index).Set(value)
}
}
// init the new controller instance.
b.init(ctx)
// call the higher "Init/BeginRequest(ctx context.Context)",
// if exists.
if customInitFuncIndex >= 0 {
callCustomFuncHandler(ctx, c, customInitFuncIndex)
}
// if custom Init didn't stop the execution of the
// context
if !ctx.IsStopped() {
// execute the responsible method for that handler.
methodFunc.Interface().(func())()
}
if !ctx.IsStopped() {
// call the higher "Done/EndRequest(ctx context.Context)",
// if exists.
if customEndFuncIndex >= 0 {
callCustomFuncHandler(ctx, c, customEndFuncIndex)
}
}
// finally, execute the controller.
b.exec()
}
}
// Useful when more than one methods are using the same
// request data.
var (
// customInitFuncNames can be used as custom functions
// to init the new instance of controller
// that is created on each new request.
// One of these is valid, no both.
customInitFuncNames = []string{"Init", "BeginRequest"}
// customEndFuncNames can be used as custom functions
// to action when the method handler has been finished,
// this is the last step before server send the response to the client.
// One of these is valid, no both.
customEndFuncNames = []string{"Done", "EndRequest"}
)
func getCustomFuncIndex(typ reflect.Type, funcNames ...string) (initFuncIndex int, has bool) {
for _, customInitFuncName := range funcNames {
if m, has := typ.MethodByName(customInitFuncName); has {
return m.Index, has
}
}
return -1, false
}
// the "cServeTime" is a new "c" instance
// which is being used at serve time, inside the Handler.
// it calls the custom function (can be "Init", "BeginRequest", "End" and "EndRequest"),
// the check of this function made at build time, so it's a safe a call.
func callCustomFuncHandler(ctx context.Context, cServeTime reflect.Value, initFuncIndex int) {
cServeTime.Method(initFuncIndex).Interface().(func(ctx context.Context))(ctx)
}

View File

@@ -1,152 +0,0 @@
// black-box testing
package router_test
import (
"testing"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/core/router"
"github.com/kataras/iris/httptest"
)
type testController struct {
router.Controller
}
var writeMethod = func(c router.Controller) {
c.Ctx.Writef(c.Ctx.Method())
}
func (c *testController) Get() {
writeMethod(c.Controller)
}
func (c *testController) Post() {
writeMethod(c.Controller)
}
func (c *testController) Put() {
writeMethod(c.Controller)
}
func (c *testController) Delete() {
writeMethod(c.Controller)
}
func (c *testController) Connect() {
writeMethod(c.Controller)
}
func (c *testController) Head() {
writeMethod(c.Controller)
}
func (c *testController) Patch() {
writeMethod(c.Controller)
}
func (c *testController) Options() {
writeMethod(c.Controller)
}
func (c *testController) Trace() {
writeMethod(c.Controller)
}
type (
testControllerAll struct{ router.Controller }
testControllerAny struct{ router.Controller } // exactly same as All
)
func (c *testControllerAll) All() {
writeMethod(c.Controller)
}
func (c *testControllerAny) All() {
writeMethod(c.Controller)
}
func TestControllerMethodFuncs(t *testing.T) {
app := iris.New()
app.Controller("/", new(testController))
app.Controller("/all", new(testControllerAll))
app.Controller("/any", new(testControllerAny))
e := httptest.New(t, app)
for _, method := range router.AllMethods {
e.Request(method, "/").Expect().Status(httptest.StatusOK).
Body().Equal(method)
e.Request(method, "/all").Expect().Status(httptest.StatusOK).
Body().Equal(method)
e.Request(method, "/any").Expect().Status(httptest.StatusOK).
Body().Equal(method)
}
}
type testControllerPersistence struct {
router.Controller
Data string `iris:"persistence"`
}
func (t *testControllerPersistence) Get() {
t.Ctx.WriteString(t.Data)
}
func TestControllerPersistenceFields(t *testing.T) {
data := "this remains the same for all requests"
app := iris.New()
app.Controller("/", &testControllerPersistence{Data: data})
e := httptest.New(t, app)
e.GET("/").Expect().Status(httptest.StatusOK).
Body().Equal(data)
}
type testControllerBeginAndEndRequestFunc struct {
router.Controller
Username string
}
// called before of every method (Get() or Post()).
//
// useful when more than one methods using the
// same request values or context's function calls.
func (t *testControllerBeginAndEndRequestFunc) BeginRequest(ctx context.Context) {
t.Username = ctx.Params().Get("username")
// or t.Params.Get("username") because the
// t.Ctx == ctx and is being initialized before this "BeginRequest"
}
// called after every method (Get() or Post()).
func (t *testControllerBeginAndEndRequestFunc) EndRequest(ctx context.Context) {
ctx.Writef("done") // append "done" to the response
}
func (t *testControllerBeginAndEndRequestFunc) Get() {
t.Ctx.Writef(t.Username)
}
func (t *testControllerBeginAndEndRequestFunc) Post() {
t.Ctx.Writef(t.Username)
}
func TestControllerBeginAndEndRequestFunc(t *testing.T) {
app := iris.New()
app.Controller("/profile/{username}", new(testControllerBeginAndEndRequestFunc))
e := httptest.New(t, app)
usernames := []string{
"kataras",
"makis",
"efi",
"rg",
"bill",
"whoisyourdaddy",
}
doneResponse := "done"
for _, username := range usernames {
e.GET("/profile/" + username).Expect().Status(httptest.StatusOK).
Body().Equal(username + doneResponse)
e.POST("/profile/" + username).Expect().Status(httptest.StatusOK).
Body().Equal(username + doneResponse)
}
}

View File

@@ -2,6 +2,7 @@ package router
import (
"github.com/kataras/iris/context"
"github.com/kataras/iris/mvc/activator"
)
// Party is here to separate the concept of
@@ -51,6 +52,22 @@ type Party interface {
//
// Returns the read-only route information.
Handle(method string, registeredPath string, handlers ...context.Handler) *Route
// HandleMany works like `Handle` but can receive more than one
// paths separated by spaces and returns always a slice of *Route instead of a single instance of Route.
//
// It's useful only if the same handler can handle more than one request paths,
// otherwise use `Party` which can handle many paths with different handlers and middlewares.
//
// Usage:
// app.HandleMany(iris.MethodGet, "/user /user/{id:int} /user/me", userHandler)
// At the other side, with `Handle` we've had to write:
// app.Handle(iris.MethodGet, "/user", userHandler)
// app.Handle(iris.MethodGet, "/user/{id:int}", userByIDHandler)
// app.Handle(iris.MethodGet, "/user/me", userMeHandler)
//
// This method is used behind the scenes at the `Controller` function
// in order to handle more than one paths for the same controller instance.
HandleMany(method string, relativePath string, handlers ...context.Handler) []*Route
// None registers an "offline" route
// see context.ExecRoute(routeName) and
@@ -107,11 +124,15 @@ type Party interface {
// It's just an alternative way of building an API for a specific
// path, the controller can register all type of http methods.
//
// Keep note that this method is a bit slow
// Keep note that controllers are bit slow
// because of the reflection use however it's as fast as possible because
// it does preparation before the serve-time handler but still
// remains slower than the low-level handlers
// such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch` .
// such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch`.
//
//
// All fields that are tagged with iris:"persistence"` or binded
// are being persistence and kept the same between the different requests.
//
// An Example Controller can be:
//
@@ -128,33 +149,29 @@ type Party interface {
// Usage: app.Controller("/", new(IndexController))
//
//
// Another example with persistence data:
// Another example with bind:
//
// type UserController struct {
// Controller
//
// CreatedAt time.Time `iris:"persistence"`
// Title string `iris:"persistence"`
// DB *DB `iris:"persistence"`
// DB *DB
// CreatedAt time.Time
//
// }
//
// // Get serves using the User controller when HTTP Method is "GET".
// func (c *UserController) Get() {
// c.Tmpl = "user/index.html"
// c.Data["title"] = c.Title
// c.Data["title"] = "User Page"
// c.Data["username"] = "kataras " + c.Params.Get("userid")
// c.Data["connstring"] = c.DB.Connstring
// c.Data["uptime"] = time.Now().Sub(c.CreatedAt).Seconds()
// }
//
// Usage: app.Controller("/user/{id:int}", &UserController{
// CreatedAt: time.Now(),
// Title: "User page",
// DB: yourDB,
// })
// Usage: app.Controller("/user/{id:int}", new(UserController), db, time.Now())
//
// Read more at `router#Controller`.
Controller(relativePath string, controller interface{}) []*Route
// Read more at `/mvc#Controller`.
Controller(relativePath string, controller activator.BaseController, bindValues ...interface{}) []*Route
// StaticHandler returns a new Handler which is ready
// to serve all kind of static files.

View File

@@ -39,6 +39,7 @@ func (ch *ErrorCodeHandler) Fire(ctx context.Context) {
return
}
}
// ctx.StopExecution() // not uncomment this, is here to remember why to.
// note for me: I don't stopping the execution of the other handlers
// because may the user want to add a fallback error code