tree.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 Unknwon
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package macaron
  16. // NOTE: last sync 90cff5f on Nov 2, 2014.
  17. import (
  18. "path"
  19. "regexp"
  20. "strings"
  21. "github.com/Unknwon/com"
  22. )
  23. type leafInfo struct {
  24. // Names of wildcards that lead to this leaf.
  25. // eg, ["id" "name"] for the wildcard ":id" and ":name".
  26. wildcards []string
  27. // Not nil if the leaf is regexp.
  28. regexps *regexp.Regexp
  29. handle Handle
  30. }
  31. func (leaf *leafInfo) match(wildcardValues []string) (ok bool, params Params) {
  32. if leaf.regexps == nil {
  33. if len(wildcardValues) == 0 && len(leaf.wildcards) > 0 {
  34. if com.IsSliceContainsStr(leaf.wildcards, ":") {
  35. params = make(map[string]string)
  36. j := 0
  37. for _, v := range leaf.wildcards {
  38. if v == ":" {
  39. continue
  40. }
  41. params[v] = ""
  42. j += 1
  43. }
  44. return true, params
  45. }
  46. return false, nil
  47. } else if len(wildcardValues) == 0 {
  48. return true, nil // Static path.
  49. }
  50. // Match *
  51. if len(leaf.wildcards) == 1 && leaf.wildcards[0] == ":splat" {
  52. params = make(map[string]string)
  53. params[":splat"] = path.Join(wildcardValues...)
  54. return true, params
  55. }
  56. // Match *.*
  57. if len(leaf.wildcards) == 3 && leaf.wildcards[0] == "." {
  58. params = make(map[string]string)
  59. lastone := wildcardValues[len(wildcardValues)-1]
  60. strs := strings.SplitN(lastone, ".", 2)
  61. if len(strs) == 2 {
  62. params[":ext"] = strs[1]
  63. } else {
  64. params[":ext"] = ""
  65. }
  66. params[":path"] = path.Join(wildcardValues[:len(wildcardValues)-1]...) + "/" + strs[0]
  67. return true, params
  68. }
  69. // Match :id
  70. params = make(map[string]string)
  71. j := 0
  72. for _, v := range leaf.wildcards {
  73. if v == ":" {
  74. continue
  75. }
  76. if v == "." {
  77. lastone := wildcardValues[len(wildcardValues)-1]
  78. strs := strings.SplitN(lastone, ".", 2)
  79. if len(strs) == 2 {
  80. params[":ext"] = strs[1]
  81. } else {
  82. params[":ext"] = ""
  83. }
  84. if len(wildcardValues[j:]) == 1 {
  85. params[":path"] = strs[0]
  86. } else {
  87. params[":path"] = path.Join(wildcardValues[j:]...) + "/" + strs[0]
  88. }
  89. return true, params
  90. }
  91. if len(wildcardValues) <= j {
  92. return false, nil
  93. }
  94. params[v] = wildcardValues[j]
  95. j++
  96. }
  97. if len(params) != len(wildcardValues) {
  98. return false, nil
  99. }
  100. return true, params
  101. }
  102. if !leaf.regexps.MatchString(path.Join(wildcardValues...)) {
  103. return false, nil
  104. }
  105. params = make(map[string]string)
  106. matches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...))
  107. for i, match := range matches[1:] {
  108. params[leaf.wildcards[i]] = match
  109. }
  110. return true, params
  111. }
  112. // Tree represents a router tree for Macaron instance.
  113. type Tree struct {
  114. fixroutes map[string]*Tree
  115. wildcard *Tree
  116. leaves []*leafInfo
  117. }
  118. // NewTree initializes and returns a router tree.
  119. func NewTree() *Tree {
  120. return &Tree{
  121. fixroutes: make(map[string]*Tree),
  122. }
  123. }
  124. // splitPath splites patthen into parts.
  125. //
  126. // Examples:
  127. // "/" -> []
  128. // "/admin" -> ["admin"]
  129. // "/admin/" -> ["admin"]
  130. // "/admin/users" -> ["admin", "users"]
  131. func splitPath(pattern string) []string {
  132. elements := strings.Split(pattern, "/")
  133. if elements[0] == "" {
  134. elements = elements[1:]
  135. }
  136. if elements[len(elements)-1] == "" {
  137. elements = elements[:len(elements)-1]
  138. }
  139. return elements
  140. }
  141. // AddRouter adds a new route to router tree.
  142. func (t *Tree) AddRouter(pattern string, handle Handle) {
  143. t.addSegments(splitPath(pattern), handle, nil, "")
  144. }
  145. // splitSegment splits segment into parts.
  146. //
  147. // Examples:
  148. // "admin" -> false, nil, ""
  149. // ":id" -> true, [:id], ""
  150. // "?:id" -> true, [: :id], "" : meaning can empty
  151. // ":id:int" -> true, [:id], ([0-9]+)
  152. // ":name:string" -> true, [:name], ([\w]+)
  153. // ":id([0-9]+)" -> true, [:id], ([0-9]+)
  154. // ":id([0-9]+)_:name" -> true, [:id :name], ([0-9]+)_(.+)
  155. // "cms_:id_:page.html" -> true, [:id :page], cms_(.+)_(.+).html
  156. // "*" -> true, [:splat], ""
  157. // "*.*" -> true,[. :path :ext], "" . meaning separator
  158. func splitSegment(key string) (bool, []string, string) {
  159. if strings.HasPrefix(key, "*") {
  160. if key == "*.*" {
  161. return true, []string{".", ":path", ":ext"}, ""
  162. } else {
  163. return true, []string{":splat"}, ""
  164. }
  165. }
  166. if strings.ContainsAny(key, ":") {
  167. var paramsNum int
  168. var out []rune
  169. var start bool
  170. var startexp bool
  171. var param []rune
  172. var expt []rune
  173. var skipnum int
  174. params := []string{}
  175. reg := regexp.MustCompile(`[a-zA-Z0-9]+`)
  176. for i, v := range key {
  177. if skipnum > 0 {
  178. skipnum -= 1
  179. continue
  180. }
  181. if start {
  182. //:id:int and :name:string
  183. if v == ':' {
  184. if len(key) >= i+4 {
  185. if key[i+1:i+4] == "int" {
  186. out = append(out, []rune("([0-9]+)")...)
  187. params = append(params, ":"+string(param))
  188. start = false
  189. startexp = false
  190. skipnum = 3
  191. param = make([]rune, 0)
  192. paramsNum += 1
  193. continue
  194. }
  195. }
  196. if len(key) >= i+7 {
  197. if key[i+1:i+7] == "string" {
  198. out = append(out, []rune(`([\w]+)`)...)
  199. params = append(params, ":"+string(param))
  200. paramsNum += 1
  201. start = false
  202. startexp = false
  203. skipnum = 6
  204. param = make([]rune, 0)
  205. continue
  206. }
  207. }
  208. }
  209. // params only support a-zA-Z0-9
  210. if reg.MatchString(string(v)) {
  211. param = append(param, v)
  212. continue
  213. }
  214. if v != '(' {
  215. out = append(out, []rune(`(.+)`)...)
  216. params = append(params, ":"+string(param))
  217. param = make([]rune, 0)
  218. paramsNum += 1
  219. start = false
  220. startexp = false
  221. }
  222. }
  223. if startexp {
  224. if v != ')' {
  225. expt = append(expt, v)
  226. continue
  227. }
  228. }
  229. if v == ':' {
  230. param = make([]rune, 0)
  231. start = true
  232. } else if v == '(' {
  233. startexp = true
  234. start = false
  235. params = append(params, ":"+string(param))
  236. paramsNum += 1
  237. expt = make([]rune, 0)
  238. expt = append(expt, '(')
  239. } else if v == ')' {
  240. startexp = false
  241. expt = append(expt, ')')
  242. out = append(out, expt...)
  243. param = make([]rune, 0)
  244. } else if v == '?' {
  245. params = append(params, ":")
  246. } else {
  247. out = append(out, v)
  248. }
  249. }
  250. if len(param) > 0 {
  251. if paramsNum > 0 {
  252. out = append(out, []rune(`(.+)`)...)
  253. }
  254. params = append(params, ":"+string(param))
  255. }
  256. return true, params, string(out)
  257. } else {
  258. return false, nil, ""
  259. }
  260. }
  261. // addSegments add segments to the router tree.
  262. func (t *Tree) addSegments(segments []string, handle Handle, wildcards []string, reg string) {
  263. // Fixed root route.
  264. if len(segments) == 0 {
  265. if reg != "" {
  266. filterCards := make([]string, 0, len(wildcards))
  267. for _, v := range wildcards {
  268. if v == ":" || v == "." {
  269. continue
  270. }
  271. filterCards = append(filterCards, v)
  272. }
  273. t.leaves = append(t.leaves, &leafInfo{
  274. handle: handle,
  275. wildcards: filterCards,
  276. regexps: regexp.MustCompile("^" + reg + "$"),
  277. })
  278. } else {
  279. t.leaves = append(t.leaves, &leafInfo{
  280. handle: handle,
  281. wildcards: wildcards,
  282. })
  283. }
  284. return
  285. }
  286. seg := segments[0]
  287. iswild, params, regexpStr := splitSegment(seg)
  288. //for the router /login/*/access match /login/2009/11/access
  289. if !iswild && com.IsSliceContainsStr(wildcards, ":splat") {
  290. iswild = true
  291. regexpStr = seg
  292. }
  293. if seg == "*" && len(wildcards) > 0 && reg == "" {
  294. iswild = true
  295. regexpStr = "(.+)"
  296. }
  297. if iswild {
  298. if t.wildcard == nil {
  299. t.wildcard = NewTree()
  300. }
  301. if regexpStr != "" {
  302. if reg == "" {
  303. rr := ""
  304. for _, w := range wildcards {
  305. if w == "." || w == ":" {
  306. continue
  307. }
  308. if w == ":splat" {
  309. rr = rr + "(.+)/"
  310. } else {
  311. rr = rr + "([^/]+)/"
  312. }
  313. }
  314. regexpStr = rr + regexpStr
  315. } else {
  316. regexpStr = "/" + regexpStr
  317. }
  318. } else if reg != "" {
  319. if seg == "*.*" {
  320. regexpStr = "/([^.]+).(.+)"
  321. } else {
  322. for _, w := range params {
  323. if w == "." || w == ":" {
  324. continue
  325. }
  326. regexpStr = "/([^/]+)" + regexpStr
  327. }
  328. }
  329. }
  330. t.wildcard.addSegments(segments[1:], handle, append(wildcards, params...), reg+regexpStr)
  331. } else {
  332. subTree, ok := t.fixroutes[seg]
  333. if !ok {
  334. subTree = NewTree()
  335. t.fixroutes[seg] = subTree
  336. }
  337. subTree.addSegments(segments[1:], handle, wildcards, reg)
  338. }
  339. }
  340. func (t *Tree) match(segments []string, wildcardValues []string) (handle Handle, params Params) {
  341. // Handle leaf nodes.
  342. if len(segments) == 0 {
  343. for _, l := range t.leaves {
  344. if ok, pa := l.match(wildcardValues); ok {
  345. return l.handle, pa
  346. }
  347. }
  348. if t.wildcard != nil {
  349. for _, l := range t.wildcard.leaves {
  350. if ok, pa := l.match(wildcardValues); ok {
  351. return l.handle, pa
  352. }
  353. }
  354. }
  355. return nil, nil
  356. }
  357. seg, segs := segments[0], segments[1:]
  358. subTree, ok := t.fixroutes[seg]
  359. if ok {
  360. handle, params = subTree.match(segs, wildcardValues)
  361. } else if len(segs) == 0 { //.json .xml
  362. if subindex := strings.LastIndex(seg, "."); subindex != -1 {
  363. subTree, ok = t.fixroutes[seg[:subindex]]
  364. if ok {
  365. handle, params = subTree.match(segs, wildcardValues)
  366. if handle != nil {
  367. if params == nil {
  368. params = make(map[string]string)
  369. }
  370. params[":ext"] = seg[subindex+1:]
  371. return handle, params
  372. }
  373. }
  374. }
  375. }
  376. if handle == nil && t.wildcard != nil {
  377. handle, params = t.wildcard.match(segs, append(wildcardValues, seg))
  378. }
  379. if handle == nil {
  380. for _, l := range t.leaves {
  381. if ok, pa := l.match(append(wildcardValues, segments...)); ok {
  382. return l.handle, pa
  383. }
  384. }
  385. }
  386. return handle, params
  387. }
  388. // Match returns Handle and params if any route is matched.
  389. func (t *Tree) Match(pattern string) (Handle, Params) {
  390. if len(pattern) == 0 || pattern[0] != '/' {
  391. return nil, nil
  392. }
  393. return t.match(splitPath(pattern), nil)
  394. }