template.go 5.9 KB

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