tree.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 0c93364 on Dec 19, 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. if len(pattern) == 0 {
  133. return []string{}
  134. }
  135. elements := strings.Split(pattern, "/")
  136. if elements[0] == "" {
  137. elements = elements[1:]
  138. }
  139. if elements[len(elements)-1] == "" {
  140. elements = elements[:len(elements)-1]
  141. }
  142. return elements
  143. }
  144. // AddRouter adds a new route to router tree.
  145. func (t *Tree) AddRouter(pattern string, handle Handle) {
  146. t.addSegments(splitPath(pattern), handle, nil, "")
  147. }
  148. // splitSegment splits segment into parts.
  149. //
  150. // Examples:
  151. // "admin" -> false, nil, ""
  152. // ":id" -> true, [:id], ""
  153. // "?:id" -> true, [: :id], "" : meaning can empty
  154. // ":id:int" -> true, [:id], ([0-9]+)
  155. // ":name:string" -> true, [:name], ([\w]+)
  156. // ":id([0-9]+)" -> true, [:id], ([0-9]+)
  157. // ":id([0-9]+)_:name" -> true, [:id :name], ([0-9]+)_(.+)
  158. // "cms_:id_:page.html" -> true, [:id :page], cms_(.+)_(.+).html
  159. // "*" -> true, [:splat], ""
  160. // "*.*" -> true,[. :path :ext], "" . meaning separator
  161. func splitSegment(key string) (bool, []string, string) {
  162. if strings.HasPrefix(key, "*") {
  163. if key == "*.*" {
  164. return true, []string{".", ":path", ":ext"}, ""
  165. } else {
  166. return true, []string{":splat"}, ""
  167. }
  168. }
  169. if strings.ContainsAny(key, ":") {
  170. var paramsNum int
  171. var out []rune
  172. var start bool
  173. var startexp bool
  174. var param []rune
  175. var expt []rune
  176. var skipnum int
  177. params := []string{}
  178. reg := regexp.MustCompile(`[a-zA-Z0-9]+`)
  179. for i, v := range key {
  180. if skipnum > 0 {
  181. skipnum -= 1
  182. continue
  183. }
  184. if start {
  185. //:id:int and :name:string
  186. if v == ':' {
  187. if len(key) >= i+4 {
  188. if key[i+1:i+4] == "int" {
  189. out = append(out, []rune("([0-9]+)")...)
  190. params = append(params, ":"+string(param))
  191. start = false
  192. startexp = false
  193. skipnum = 3
  194. param = make([]rune, 0)
  195. paramsNum += 1
  196. continue
  197. }
  198. }
  199. if len(key) >= i+7 {
  200. if key[i+1:i+7] == "string" {
  201. out = append(out, []rune(`([\w]+)`)...)
  202. params = append(params, ":"+string(param))
  203. paramsNum += 1
  204. start = false
  205. startexp = false
  206. skipnum = 6
  207. param = make([]rune, 0)
  208. continue
  209. }
  210. }
  211. }
  212. // params only support a-zA-Z0-9
  213. if reg.MatchString(string(v)) {
  214. param = append(param, v)
  215. continue
  216. }
  217. if v != '(' {
  218. out = append(out, []rune(`(.+)`)...)
  219. params = append(params, ":"+string(param))
  220. param = make([]rune, 0)
  221. paramsNum += 1
  222. start = false
  223. startexp = false
  224. }
  225. }
  226. if startexp {
  227. if v != ')' {
  228. expt = append(expt, v)
  229. continue
  230. }
  231. }
  232. if v == ':' {
  233. param = make([]rune, 0)
  234. start = true
  235. } else if v == '(' {
  236. startexp = true
  237. start = false
  238. params = append(params, ":"+string(param))
  239. paramsNum += 1
  240. expt = make([]rune, 0)
  241. expt = append(expt, '(')
  242. } else if v == ')' {
  243. startexp = false
  244. expt = append(expt, ')')
  245. out = append(out, expt...)
  246. param = make([]rune, 0)
  247. } else if v == '?' {
  248. params = append(params, ":")
  249. } else {
  250. out = append(out, v)
  251. }
  252. }
  253. if len(param) > 0 {
  254. if paramsNum > 0 {
  255. out = append(out, []rune(`(.+)`)...)
  256. }
  257. params = append(params, ":"+string(param))
  258. }
  259. return true, params, string(out)
  260. } else {
  261. return false, nil, ""
  262. }
  263. }
  264. // addSegments add segments to the router tree.
  265. func (t *Tree) addSegments(segments []string, handle Handle, wildcards []string, reg string) {
  266. // Fixed root route.
  267. if len(segments) == 0 {
  268. if reg != "" {
  269. filterCards := make([]string, 0, len(wildcards))
  270. for _, v := range wildcards {
  271. if v == ":" || v == "." {
  272. continue
  273. }
  274. filterCards = append(filterCards, v)
  275. }
  276. t.leaves = append(t.leaves, &leafInfo{
  277. handle: handle,
  278. wildcards: filterCards,
  279. regexps: regexp.MustCompile("^" + reg + "$"),
  280. })
  281. } else {
  282. t.leaves = append(t.leaves, &leafInfo{
  283. handle: handle,
  284. wildcards: wildcards,
  285. })
  286. }
  287. return
  288. }
  289. seg := segments[0]
  290. iswild, params, regexpStr := splitSegment(seg)
  291. //for the router /login/*/access match /login/2009/11/access
  292. if !iswild && com.IsSliceContainsStr(wildcards, ":splat") {
  293. iswild = true
  294. regexpStr = seg
  295. }
  296. if seg == "*" && len(wildcards) > 0 && reg == "" {
  297. iswild = true
  298. regexpStr = "(.+)"
  299. }
  300. if iswild {
  301. if t.wildcard == nil {
  302. t.wildcard = NewTree()
  303. }
  304. if regexpStr != "" {
  305. if reg == "" {
  306. rr := ""
  307. for _, w := range wildcards {
  308. if w == "." || w == ":" {
  309. continue
  310. }
  311. if w == ":splat" {
  312. rr = rr + "(.+)/"
  313. } else {
  314. rr = rr + "([^/]+)/"
  315. }
  316. }
  317. regexpStr = rr + regexpStr
  318. } else {
  319. regexpStr = "/" + regexpStr
  320. }
  321. } else if reg != "" {
  322. if seg == "*.*" {
  323. regexpStr = "/([^.]+).(.+)"
  324. } else {
  325. for _, w := range params {
  326. if w == "." || w == ":" {
  327. continue
  328. }
  329. regexpStr = "/([^/]+)" + regexpStr
  330. }
  331. }
  332. }
  333. t.wildcard.addSegments(segments[1:], handle, append(wildcards, params...), reg+regexpStr)
  334. } else {
  335. subTree, ok := t.fixroutes[seg]
  336. if !ok {
  337. subTree = NewTree()
  338. t.fixroutes[seg] = subTree
  339. }
  340. subTree.addSegments(segments[1:], handle, wildcards, reg)
  341. }
  342. }
  343. func (t *Tree) match(segments []string, wildcardValues []string) (handle Handle, params Params) {
  344. // Handle leaf nodes.
  345. if len(segments) == 0 {
  346. for _, l := range t.leaves {
  347. if ok, pa := l.match(wildcardValues); ok {
  348. return l.handle, pa
  349. }
  350. }
  351. if t.wildcard != nil {
  352. for _, l := range t.wildcard.leaves {
  353. if ok, pa := l.match(wildcardValues); ok {
  354. return l.handle, pa
  355. }
  356. }
  357. }
  358. return nil, nil
  359. }
  360. seg, segs := segments[0], segments[1:]
  361. subTree, ok := t.fixroutes[seg]
  362. if ok {
  363. handle, params = subTree.match(segs, wildcardValues)
  364. } else if len(segs) == 0 { //.json .xml
  365. if subindex := strings.LastIndex(seg, "."); subindex != -1 {
  366. subTree, ok = t.fixroutes[seg[:subindex]]
  367. if ok {
  368. handle, params = subTree.match(segs, wildcardValues)
  369. if handle != nil {
  370. if params == nil {
  371. params = make(map[string]string)
  372. }
  373. params[":ext"] = seg[subindex+1:]
  374. return handle, params
  375. }
  376. }
  377. }
  378. }
  379. if handle == nil && t.wildcard != nil {
  380. handle, params = t.wildcard.match(segs, append(wildcardValues, seg))
  381. }
  382. if handle == nil {
  383. for _, l := range t.leaves {
  384. if ok, pa := l.match(append(wildcardValues, segments...)); ok {
  385. return l.handle, pa
  386. }
  387. }
  388. }
  389. return handle, params
  390. }
  391. // Match returns Handle and params if any route is matched.
  392. func (t *Tree) Match(pattern string) (Handle, Params) {
  393. if len(pattern) == 0 || pattern[0] != '/' {
  394. return nil, nil
  395. }
  396. return t.match(splitPath(pattern), nil)
  397. }