controller_method_parser.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package mvc
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "unicode"
  9. "github.com/kataras/iris/v12/core/router"
  10. "github.com/kataras/iris/v12/macro"
  11. )
  12. const (
  13. tokenBy = "By"
  14. tokenWildcard = "Wildcard" // "ByWildcard".
  15. )
  16. // word lexer, not characters.
  17. type methodLexer struct {
  18. words []string
  19. cur int
  20. }
  21. func newMethodLexer(s string) *methodLexer {
  22. l := new(methodLexer)
  23. l.reset(s)
  24. return l
  25. }
  26. /*
  27. var allowedCapitalWords = map[string]struct{}{
  28. "ID": {},
  29. "JSON": {},
  30. }
  31. */
  32. func (l *methodLexer) reset(s string) {
  33. l.cur = -1
  34. var words []string
  35. if s != "" {
  36. end := len(s)
  37. start := -1
  38. // outter:
  39. for i, n := 0, end; i < n; i++ {
  40. c := rune(s[i])
  41. if unicode.IsUpper(c) {
  42. // it doesn't count the last uppercase
  43. if start != -1 {
  44. /*
  45. for allowedCapitalWord := range allowedCapitalWords {
  46. capitalWordEnd := i + len(allowedCapitalWord) // takes last char too, e.g. ReadJSON, we need the JSON.
  47. if len(s) >= capitalWordEnd {
  48. word := s[i:capitalWordEnd]
  49. if word == allowedCapitalWord {
  50. words = append(words, word)
  51. i = capitalWordEnd
  52. start = i
  53. continue outter
  54. }
  55. }
  56. }
  57. */
  58. end = i
  59. words = append(words, s[start:end])
  60. }
  61. start = i
  62. continue
  63. }
  64. end = i + 1
  65. }
  66. if end > 0 && len(s) >= end {
  67. words = append(words, s[start:])
  68. }
  69. }
  70. l.words = words
  71. }
  72. func (l *methodLexer) next() (w string) {
  73. cur := l.cur + 1
  74. if w = l.peek(cur); w != "" {
  75. l.cur++
  76. }
  77. return
  78. }
  79. func (l *methodLexer) skip() {
  80. if cur := l.cur + 1; cur < len(l.words) {
  81. l.cur = cur
  82. } else {
  83. l.cur = len(l.words) - 1
  84. }
  85. }
  86. func (l *methodLexer) peek(idx int) string {
  87. if idx < len(l.words) {
  88. return l.words[idx]
  89. }
  90. return ""
  91. }
  92. func (l *methodLexer) peekNext() (w string) {
  93. return l.peek(l.cur + 1)
  94. }
  95. func genParamKey(argIdx int) string {
  96. return "param" + strconv.Itoa(argIdx) // param0, param1, param2...
  97. }
  98. type methodParser struct {
  99. lexer *methodLexer
  100. fn reflect.Method
  101. macros *macro.Macros
  102. customPathWordFunc CustomPathWordFunc
  103. }
  104. func parseMethod(macros *macro.Macros, fn reflect.Method, skipper func(string) bool, wordFunc CustomPathWordFunc) (method, path string, err error) {
  105. if skipper(fn.Name) {
  106. return "", "", errSkip
  107. }
  108. p := &methodParser{
  109. fn: fn,
  110. lexer: newMethodLexer(fn.Name),
  111. macros: macros,
  112. customPathWordFunc: wordFunc,
  113. }
  114. return p.parse()
  115. }
  116. func methodTitle(httpMethod string) string {
  117. httpMethodFuncName := strings.Title(strings.ToLower(httpMethod))
  118. return httpMethodFuncName
  119. }
  120. var errSkip = errors.New("skip")
  121. var allMethods = append(router.AllMethods[0:], []string{"ALL", "ANY"}...)
  122. // CustomPathWordFunc describes the function which can be passed
  123. // through `Application.SetCustomPathWordFunc` to customize
  124. // the controllers method parsing.
  125. type CustomPathWordFunc func(path, w string, wordIndex int) string
  126. func addPathWord(path, w string) string {
  127. if path[len(path)-1] != '/' {
  128. path += "/"
  129. }
  130. path += strings.ToLower(w)
  131. return path
  132. }
  133. func (p *methodParser) parse() (method, path string, err error) {
  134. funcArgPos := 0
  135. path = "/"
  136. // take the first word and check for the method.
  137. w := p.lexer.next()
  138. for _, httpMethod := range allMethods {
  139. possibleMethodFuncName := methodTitle(httpMethod)
  140. if strings.Index(w, possibleMethodFuncName) == 0 {
  141. method = httpMethod
  142. break
  143. }
  144. }
  145. if method == "" {
  146. // this is not a valid method to parse, we just skip it,
  147. // it may be used for end-dev's use cases.
  148. return "", "", errSkip
  149. }
  150. wordIndex := 0
  151. for {
  152. w := p.lexer.next()
  153. if w == "" {
  154. break
  155. }
  156. if w == tokenBy {
  157. funcArgPos++ // starting with 1 because in typ.NumIn() the first is the struct receiver.
  158. // No need for these:
  159. // ByBy will act like /{param:type}/{param:type} as users expected
  160. // if func input arguments are there, else act By like normal path /by.
  161. //
  162. // if p.lexer.peekPrev() == tokenBy || typ.NumIn() == 1 { // ByBy, then act this second By like a path
  163. // a.relPath += "/" + strings.ToLower(w)
  164. // continue
  165. // }
  166. if path, funcArgPos, err = p.parsePathParam(path, w, funcArgPos); err != nil {
  167. return "", "", err
  168. }
  169. continue
  170. }
  171. // custom static path.
  172. if p.customPathWordFunc != nil {
  173. path = p.customPathWordFunc(path, w, wordIndex)
  174. } else {
  175. // default static path.
  176. path = addPathWord(path, w)
  177. }
  178. wordIndex++
  179. }
  180. return
  181. }
  182. func (p *methodParser) parsePathParam(path string, w string, funcArgPos int) (string, int, error) {
  183. typ := p.fn.Type
  184. if typ.NumIn() <= funcArgPos {
  185. // By found but input arguments are not there, so act like /by path without restricts.
  186. path = addPathWord(path, w)
  187. return path, funcArgPos, nil
  188. }
  189. var (
  190. paramKey = genParamKey(funcArgPos) // argfirst, argsecond...
  191. m = p.macros.GetMaster() // default (String by-default)
  192. trailings = p.macros.GetTrailings()
  193. )
  194. // string, int...
  195. goType := typ.In(funcArgPos).Kind()
  196. nextWord := p.lexer.peekNext()
  197. if nextWord == tokenWildcard {
  198. p.lexer.skip() // skip the Wildcard word.
  199. if len(trailings) == 0 {
  200. return "", 0, errors.New("no trailing path parameter found")
  201. }
  202. m = trailings[0]
  203. } else {
  204. // validMacros := p.macros.LookupForGoType(goType)
  205. // instead of mapping with a reflect.Kind which has its limitation,
  206. // we map the param types with a go type as a string,
  207. // so custom structs such as "user" can be mapped to a macro with indent || alias == "user".
  208. m = p.macros.Get(strings.ToLower(goType.String()))
  209. if m == nil {
  210. if typ.NumIn() > funcArgPos {
  211. // has more input arguments but we are not in the correct
  212. // index now, maybe the first argument was an `iris/context.Context`
  213. // so retry with the "funcArgPos" incremented.
  214. //
  215. // the "funcArgPos" will be updated to the caller as well
  216. // because we return it among the path and the error.
  217. return p.parsePathParam(path, w, funcArgPos+1)
  218. }
  219. return "", 0, fmt.Errorf("invalid syntax: the standard go type: %s found in controller's function: %s at position: %d does not match any valid macro", goType, p.fn.Name, funcArgPos)
  220. }
  221. }
  222. // /{argfirst:path}, /{argfirst:int64}...
  223. if path[len(path)-1] != '/' {
  224. path += "/"
  225. }
  226. path += fmt.Sprintf("{%s:%s}", paramKey, m.Indent())
  227. if nextWord == "" && typ.NumIn() > funcArgPos+1 {
  228. // By is the latest word but func is expected
  229. // more path parameters values, i.e:
  230. // GetBy(name string, age int)
  231. // The caller (parse) doesn't need to know
  232. // about the incremental funcArgPos because
  233. // it will not need it.
  234. return p.parsePathParam(path, nextWord, funcArgPos+1)
  235. }
  236. return path, funcArgPos, nil
  237. }