2017-08-18 16:09:18 +02:00
|
|
|
package activator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
"github.com/kataras/iris/context"
|
|
|
|
)
|
|
|
|
|
|
|
|
type modelControl struct {
|
|
|
|
fields []field
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mc *modelControl) Load(t *TController) error {
|
2017-08-23 00:11:52 +02:00
|
|
|
matcher := func(f reflect.StructField) bool {
|
2017-08-18 16:09:18 +02:00
|
|
|
if tag, ok := f.Tag.Lookup("iris"); ok {
|
|
|
|
if tag == "model" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2017-08-23 00:11:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fields := lookupFields(t.Type.Elem(), matcher, nil)
|
2017-08-18 16:09:18 +02:00
|
|
|
|
|
|
|
if len(fields) == 0 {
|
|
|
|
// first is the `Controller` so we need to
|
|
|
|
// check the second and after that.
|
|
|
|
return ErrControlSkip
|
|
|
|
}
|
|
|
|
|
|
|
|
mc.fields = fields
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mc *modelControl) Handle(ctx context.Context, c reflect.Value, methodFunc func()) {
|
|
|
|
elem := c.Elem() // controller should always be a pointer at this state
|
|
|
|
|
|
|
|
for _, f := range mc.fields {
|
2017-08-23 00:11:52 +02:00
|
|
|
|
|
|
|
index := f.getIndex()
|
|
|
|
typ := f.getType()
|
|
|
|
name := f.getTagName()
|
|
|
|
|
|
|
|
elemField := elem.FieldByIndex(index)
|
2017-08-18 16:09:18 +02:00
|
|
|
// check if current controller's element field
|
|
|
|
// is valid, is not nil and it's type is the same (should be but make that check to be sure).
|
2017-08-23 00:11:52 +02:00
|
|
|
if !elemField.IsValid() ||
|
|
|
|
(elemField.Kind() == reflect.Ptr && elemField.IsNil()) ||
|
|
|
|
elemField.Type() != typ {
|
2017-08-18 16:09:18 +02:00
|
|
|
continue
|
|
|
|
}
|
2017-08-23 00:11:52 +02:00
|
|
|
|
2017-08-18 16:09:18 +02:00
|
|
|
fieldValue := elemField.Interface()
|
2017-08-23 00:11:52 +02:00
|
|
|
ctx.ViewData(name, fieldValue)
|
2017-08-18 16:09:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ModelControl returns a TControl which is responsible
|
|
|
|
// to load and handle the `Model(s)` inside a controller struct
|
|
|
|
// via the `iris:"model"` tag field.
|
|
|
|
func ModelControl() TControl {
|
|
|
|
return &modelControl{}
|
|
|
|
}
|