template.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package macro
  2. import (
  3. "reflect"
  4. "github.com/kataras/iris/macro/interpreter/ast"
  5. "github.com/kataras/iris/macro/interpreter/parser"
  6. )
  7. // Template contains a route's path full parsed template.
  8. //
  9. // Fields:
  10. // Src is the raw source of the path, i.e /users/{id:int min(1)}
  11. // Params is the list of the Params that are being used to the
  12. // path, i.e the min as param name and 1 as the param argument.
  13. type Template struct {
  14. // Src is the original template given by the client
  15. Src string `json:"src"`
  16. Params []TemplateParam `json:"params"`
  17. }
  18. // IsTrailing reports whether this Template is a traling one.
  19. func (t *Template) IsTrailing() bool {
  20. return len(t.Params) > 0 && ast.IsTrailing(t.Params[len(t.Params)-1].Type)
  21. }
  22. // TemplateParam is the parsed macro parameter's template
  23. // they are being used to describe the param's syntax result.
  24. type TemplateParam struct {
  25. Src string `json:"src"` // the unparsed param'false source
  26. // Type is not useful anywhere here but maybe
  27. // it's useful on host to decide how to convert the path template to specific router's syntax
  28. Type ast.ParamType `json:"type"`
  29. Name string `json:"name"`
  30. Index int `json:"index"`
  31. ErrCode int `json:"errCode"`
  32. TypeEvaluator ParamEvaluator `json:"-"`
  33. Funcs []reflect.Value `json:"-"`
  34. stringInFuncs []func(string) bool
  35. canEval bool
  36. }
  37. func (p TemplateParam) preComputed() TemplateParam {
  38. for _, pfn := range p.Funcs {
  39. if fn, ok := pfn.Interface().(func(string) bool); ok {
  40. p.stringInFuncs = append(p.stringInFuncs, fn)
  41. }
  42. }
  43. // if true then it should be execute the type parameter or its functions
  44. // else it can be ignored,
  45. // i.e {myparam} or {myparam:string} or {myparam:path} ->
  46. // their type evaluator is nil because they don't do any checks and they don't change
  47. // the default parameter value's type (string) so no need for any work).
  48. p.canEval = p.TypeEvaluator != nil || len(p.Funcs) > 0 || p.ErrCode != parser.DefaultParamErrorCode
  49. return p
  50. }
  51. // CanEval returns true if this "p" TemplateParam should be evaluated in serve time.
  52. // It is computed before server ran and it is used to determinate if a route needs to build a macro handler (middleware).
  53. func (p *TemplateParam) CanEval() bool {
  54. return p.canEval
  55. }
  56. // Eval is the most critical part of the TemplateParam.
  57. // It is responsible to return the type-based value if passed otherwise nil.
  58. // If the "paramValue" is the correct type of the registered parameter type
  59. // and all functions, if any, are passed.
  60. //
  61. // It is called from the converted macro handler (middleware)
  62. // from the higher-level component of "kataras/iris/macro/handler#MakeHandler".
  63. func (p *TemplateParam) Eval(paramValue string) interface{} {
  64. if p.TypeEvaluator == nil {
  65. for _, fn := range p.stringInFuncs {
  66. if !fn(paramValue) {
  67. return nil
  68. }
  69. }
  70. return paramValue
  71. }
  72. // fmt.Printf("macro/template.go#L88: Eval for param value: %s and p.Src: %s\n", paramValue, p.Src)
  73. newValue, passed := p.TypeEvaluator(paramValue)
  74. if !passed {
  75. return nil
  76. }
  77. if len(p.Funcs) > 0 {
  78. paramIn := []reflect.Value{reflect.ValueOf(newValue)}
  79. for _, evalFunc := range p.Funcs {
  80. // or make it as func(interface{}) bool and pass directly the "newValue"
  81. // but that would not be as easy for end-developer, so keep that "slower":
  82. if !evalFunc.Call(paramIn)[0].Interface().(bool) { // i.e func(paramValue int) bool
  83. return nil
  84. }
  85. }
  86. }
  87. // fmt.Printf("macro/template.go: passed with value: %v and type: %T\n", newValue, newValue)
  88. return newValue
  89. }
  90. // Parse takes a full route path and a macro map (macro map contains the macro types with their registered param functions)
  91. // and returns a new Template.
  92. // It builds all the parameter functions for that template
  93. // and their evaluators, it's the api call that makes use the interpeter's parser -> lexer.
  94. func Parse(src string, macros Macros) (Template, error) {
  95. types := make([]ast.ParamType, len(macros))
  96. for i, m := range macros {
  97. types[i] = m
  98. }
  99. tmpl := Template{Src: src}
  100. params, err := parser.Parse(src, types)
  101. if err != nil {
  102. return tmpl, err
  103. }
  104. for idx, p := range params {
  105. m := macros.Lookup(p.Type)
  106. typEval := m.Evaluator
  107. tmplParam := TemplateParam{
  108. Src: p.Src,
  109. Type: p.Type,
  110. Name: p.Name,
  111. Index: idx,
  112. ErrCode: p.ErrorCode,
  113. TypeEvaluator: typEval,
  114. }
  115. for _, paramfn := range p.Funcs {
  116. tmplFn := m.getFunc(paramfn.Name)
  117. if tmplFn == nil { // if not find on this type, check for Master's which is for global funcs too.
  118. if m := macros.GetMaster(); m != nil {
  119. tmplFn = m.getFunc(paramfn.Name)
  120. }
  121. if tmplFn == nil { // if not found then just skip this param.
  122. continue
  123. }
  124. }
  125. evalFn := tmplFn(paramfn.Args)
  126. if evalFn.IsNil() || !evalFn.IsValid() || evalFn.Kind() != reflect.Func {
  127. continue
  128. }
  129. tmplParam.Funcs = append(tmplParam.Funcs, evalFn)
  130. }
  131. tmpl.Params = append(tmpl.Params, tmplParam.preComputed())
  132. }
  133. return tmpl, nil
  134. }
  135. // CountParams returns the length of the dynamic path's input parameters.
  136. func CountParams(fullpath string, macros Macros) int {
  137. tmpl, _ := Parse(fullpath, macros)
  138. return len(tmpl.Params)
  139. }