controller_method_parser.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package mvc
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "strings"
  7. "unicode"
  8. "github.com/kataras/iris/core/router"
  9. "github.com/kataras/iris/core/router/macro/interpreter/ast"
  10. )
  11. const (
  12. tokenBy = "By"
  13. tokenWildcard = "Wildcard" // "ByWildcard".
  14. )
  15. // word lexer, not characters.
  16. type methodLexer struct {
  17. words []string
  18. cur int
  19. }
  20. func newMethodLexer(s string) *methodLexer {
  21. l := new(methodLexer)
  22. l.reset(s)
  23. return l
  24. }
  25. func (l *methodLexer) reset(s string) {
  26. l.cur = -1
  27. var words []string
  28. if s != "" {
  29. end := len(s)
  30. start := -1
  31. for i, n := 0, end; i < n; i++ {
  32. c := rune(s[i])
  33. if unicode.IsUpper(c) {
  34. // it doesn't count the last uppercase
  35. if start != -1 {
  36. end = i
  37. words = append(words, s[start:end])
  38. }
  39. start = i
  40. continue
  41. }
  42. end = i + 1
  43. }
  44. if end > 0 && len(s) >= end {
  45. words = append(words, s[start:end])
  46. }
  47. }
  48. l.words = words
  49. }
  50. func (l *methodLexer) next() (w string) {
  51. cur := l.cur + 1
  52. if w = l.peek(cur); w != "" {
  53. l.cur++
  54. }
  55. return
  56. }
  57. func (l *methodLexer) skip() {
  58. if cur := l.cur + 1; cur < len(l.words) {
  59. l.cur = cur
  60. } else {
  61. l.cur = len(l.words) - 1
  62. }
  63. }
  64. func (l *methodLexer) peek(idx int) string {
  65. if idx < len(l.words) {
  66. return l.words[idx]
  67. }
  68. return ""
  69. }
  70. func (l *methodLexer) peekNext() (w string) {
  71. return l.peek(l.cur + 1)
  72. }
  73. func (l *methodLexer) peekPrev() (w string) {
  74. if l.cur > 0 {
  75. cur := l.cur - 1
  76. w = l.words[cur]
  77. }
  78. return w
  79. }
  80. var posWords = map[int]string{
  81. 0: "",
  82. 1: "first",
  83. 2: "second",
  84. 3: "third",
  85. 4: "forth",
  86. 5: "five",
  87. 6: "sixth",
  88. 7: "seventh",
  89. 8: "eighth",
  90. 9: "ninth",
  91. 10: "tenth",
  92. 11: "eleventh",
  93. 12: "twelfth",
  94. 13: "thirteenth",
  95. 14: "fourteenth",
  96. 15: "fifteenth",
  97. 16: "sixteenth",
  98. 17: "seventeenth",
  99. 18: "eighteenth",
  100. 19: "nineteenth",
  101. 20: "twentieth",
  102. }
  103. func genParamKey(argIdx int) string {
  104. return "arg" + posWords[argIdx] // argfirst, argsecond...
  105. }
  106. type methodParser struct {
  107. lexer *methodLexer
  108. fn reflect.Method
  109. }
  110. func parseMethod(fn reflect.Method, skipper func(string) bool) (method, path string, err error) {
  111. if skipper(fn.Name) {
  112. return "", "", errSkip
  113. }
  114. p := &methodParser{
  115. fn: fn,
  116. lexer: newMethodLexer(fn.Name),
  117. }
  118. return p.parse()
  119. }
  120. func methodTitle(httpMethod string) string {
  121. httpMethodFuncName := strings.Title(strings.ToLower(httpMethod))
  122. return httpMethodFuncName
  123. }
  124. var errSkip = errors.New("skip")
  125. var allMethods = append(router.AllMethods[0:], []string{"ALL", "ANY"}...)
  126. func (p *methodParser) parse() (method, path string, err error) {
  127. funcArgPos := 0
  128. path = "/"
  129. // take the first word and check for the method.
  130. w := p.lexer.next()
  131. for _, httpMethod := range allMethods {
  132. possibleMethodFuncName := methodTitle(httpMethod)
  133. if strings.Index(w, possibleMethodFuncName) == 0 {
  134. method = httpMethod
  135. break
  136. }
  137. }
  138. if method == "" {
  139. // this is not a valid method to parse, we just skip it,
  140. // it may be used for end-dev's use cases.
  141. return "", "", errSkip
  142. }
  143. for {
  144. w := p.lexer.next()
  145. if w == "" {
  146. break
  147. }
  148. if w == tokenBy {
  149. funcArgPos++ // starting with 1 because in typ.NumIn() the first is the struct receiver.
  150. // No need for these:
  151. // ByBy will act like /{param:type}/{param:type} as users expected
  152. // if func input arguments are there, else act By like normal path /by.
  153. //
  154. // if p.lexer.peekPrev() == tokenBy || typ.NumIn() == 1 { // ByBy, then act this second By like a path
  155. // a.relPath += "/" + strings.ToLower(w)
  156. // continue
  157. // }
  158. if path, funcArgPos, err = p.parsePathParam(path, w, funcArgPos); err != nil {
  159. return "", "", err
  160. }
  161. continue
  162. }
  163. // static path.
  164. path += "/" + strings.ToLower(w)
  165. }
  166. return
  167. }
  168. func (p *methodParser) parsePathParam(path string, w string, funcArgPos int) (string, int, error) {
  169. typ := p.fn.Type
  170. if typ.NumIn() <= funcArgPos {
  171. // By found but input arguments are not there, so act like /by path without restricts.
  172. path += "/" + strings.ToLower(w)
  173. return path, funcArgPos, nil
  174. }
  175. var (
  176. paramKey = genParamKey(funcArgPos) // argfirst, argsecond...
  177. paramType = ast.ParamTypeString // default string
  178. )
  179. // string, int...
  180. goType := typ.In(funcArgPos).Name()
  181. nextWord := p.lexer.peekNext()
  182. if nextWord == tokenWildcard {
  183. p.lexer.skip() // skip the Wildcard word.
  184. paramType = ast.ParamTypePath
  185. } else if pType := ast.LookupParamTypeFromStd(goType); pType != ast.ParamTypeUnExpected {
  186. // it's not wildcard, so check base on our available macro types.
  187. paramType = pType
  188. } else {
  189. if typ.NumIn() > funcArgPos {
  190. // has more input arguments but we are not in the correct
  191. // index now, maybe the first argument was an `iris/context.Context`
  192. // so retry with the "funcArgPos" incremented.
  193. //
  194. // the "funcArgPos" will be updated to the caller as well
  195. // because we return it among the path and the error.
  196. return p.parsePathParam(path, w, funcArgPos+1)
  197. }
  198. return "", 0, errors.New("invalid syntax for " + p.fn.Name)
  199. }
  200. // /{argfirst:path}, /{argfirst:long}...
  201. path += fmt.Sprintf("/{%s:%s}", paramKey, paramType.String())
  202. if nextWord == "" && typ.NumIn() > funcArgPos+1 {
  203. // By is the latest word but func is expected
  204. // more path parameters values, i.e:
  205. // GetBy(name string, age int)
  206. // The caller (parse) doesn't need to know
  207. // about the incremental funcArgPos because
  208. // it will not need it.
  209. return p.parsePathParam(path, nextWord, funcArgPos+1)
  210. }
  211. return path, funcArgPos, nil
  212. }