tree.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "path"
  17. "regexp"
  18. "strings"
  19. "github.com/cnlh/nps/vender/github.com/astaxie/beego/context"
  20. "github.com/cnlh/nps/vender/github.com/astaxie/beego/utils"
  21. )
  22. var (
  23. allowSuffixExt = []string{".json", ".xml", ".html"}
  24. )
  25. // Tree has three elements: FixRouter/wildcard/leaves
  26. // fixRouter stores Fixed Router
  27. // wildcard stores params
  28. // leaves store the endpoint information
  29. type Tree struct {
  30. //prefix set for static router
  31. prefix string
  32. //search fix route first
  33. fixrouters []*Tree
  34. //if set, failure to match fixrouters search then search wildcard
  35. wildcard *Tree
  36. //if set, failure to match wildcard search
  37. leaves []*leafInfo
  38. }
  39. // NewTree return a new Tree
  40. func NewTree() *Tree {
  41. return &Tree{}
  42. }
  43. // AddTree will add tree to the exist Tree
  44. // prefix should has no params
  45. func (t *Tree) AddTree(prefix string, tree *Tree) {
  46. t.addtree(splitPath(prefix), tree, nil, "")
  47. }
  48. func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg string) {
  49. if len(segments) == 0 {
  50. panic("prefix should has path")
  51. }
  52. seg := segments[0]
  53. iswild, params, regexpStr := splitSegment(seg)
  54. // if it's ? meaning can igone this, so add one more rule for it
  55. if len(params) > 0 && params[0] == ":" {
  56. params = params[1:]
  57. if len(segments[1:]) > 0 {
  58. t.addtree(segments[1:], tree, append(wildcards, params...), reg)
  59. } else {
  60. filterTreeWithPrefix(tree, wildcards, reg)
  61. }
  62. }
  63. //Rule: /login/*/access match /login/2009/11/access
  64. //if already has *, and when loop the access, should as a regexpStr
  65. if !iswild && utils.InSlice(":splat", wildcards) {
  66. iswild = true
  67. regexpStr = seg
  68. }
  69. //Rule: /user/:id/*
  70. if seg == "*" && len(wildcards) > 0 && reg == "" {
  71. regexpStr = "(.+)"
  72. }
  73. if len(segments) == 1 {
  74. if iswild {
  75. if regexpStr != "" {
  76. if reg == "" {
  77. rr := ""
  78. for _, w := range wildcards {
  79. if w == ":splat" {
  80. rr = rr + "(.+)/"
  81. } else {
  82. rr = rr + "([^/]+)/"
  83. }
  84. }
  85. regexpStr = rr + regexpStr
  86. } else {
  87. regexpStr = "/" + regexpStr
  88. }
  89. } else if reg != "" {
  90. if seg == "*.*" {
  91. regexpStr = "([^.]+).(.+)"
  92. } else {
  93. for _, w := range params {
  94. if w == "." || w == ":" {
  95. continue
  96. }
  97. regexpStr = "([^/]+)/" + regexpStr
  98. }
  99. }
  100. }
  101. reg = strings.Trim(reg+"/"+regexpStr, "/")
  102. filterTreeWithPrefix(tree, append(wildcards, params...), reg)
  103. t.wildcard = tree
  104. } else {
  105. reg = strings.Trim(reg+"/"+regexpStr, "/")
  106. filterTreeWithPrefix(tree, append(wildcards, params...), reg)
  107. tree.prefix = seg
  108. t.fixrouters = append(t.fixrouters, tree)
  109. }
  110. return
  111. }
  112. if iswild {
  113. if t.wildcard == nil {
  114. t.wildcard = NewTree()
  115. }
  116. if regexpStr != "" {
  117. if reg == "" {
  118. rr := ""
  119. for _, w := range wildcards {
  120. if w == ":splat" {
  121. rr = rr + "(.+)/"
  122. } else {
  123. rr = rr + "([^/]+)/"
  124. }
  125. }
  126. regexpStr = rr + regexpStr
  127. } else {
  128. regexpStr = "/" + regexpStr
  129. }
  130. } else if reg != "" {
  131. if seg == "*.*" {
  132. regexpStr = "([^.]+).(.+)"
  133. params = params[1:]
  134. } else {
  135. for range params {
  136. regexpStr = "([^/]+)/" + regexpStr
  137. }
  138. }
  139. } else {
  140. if seg == "*.*" {
  141. params = params[1:]
  142. }
  143. }
  144. reg = strings.TrimRight(strings.TrimRight(reg, "/")+"/"+regexpStr, "/")
  145. t.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg)
  146. } else {
  147. subTree := NewTree()
  148. subTree.prefix = seg
  149. t.fixrouters = append(t.fixrouters, subTree)
  150. subTree.addtree(segments[1:], tree, append(wildcards, params...), reg)
  151. }
  152. }
  153. func filterTreeWithPrefix(t *Tree, wildcards []string, reg string) {
  154. for _, v := range t.fixrouters {
  155. filterTreeWithPrefix(v, wildcards, reg)
  156. }
  157. if t.wildcard != nil {
  158. filterTreeWithPrefix(t.wildcard, wildcards, reg)
  159. }
  160. for _, l := range t.leaves {
  161. if reg != "" {
  162. if l.regexps != nil {
  163. l.wildcards = append(wildcards, l.wildcards...)
  164. l.regexps = regexp.MustCompile("^" + reg + "/" + strings.Trim(l.regexps.String(), "^$") + "$")
  165. } else {
  166. for _, v := range l.wildcards {
  167. if v == ":splat" {
  168. reg = reg + "/(.+)"
  169. } else {
  170. reg = reg + "/([^/]+)"
  171. }
  172. }
  173. l.regexps = regexp.MustCompile("^" + reg + "$")
  174. l.wildcards = append(wildcards, l.wildcards...)
  175. }
  176. } else {
  177. l.wildcards = append(wildcards, l.wildcards...)
  178. if l.regexps != nil {
  179. for _, w := range wildcards {
  180. if w == ":splat" {
  181. reg = "(.+)/" + reg
  182. } else {
  183. reg = "([^/]+)/" + reg
  184. }
  185. }
  186. l.regexps = regexp.MustCompile("^" + reg + strings.Trim(l.regexps.String(), "^$") + "$")
  187. }
  188. }
  189. }
  190. }
  191. // AddRouter call addseg function
  192. func (t *Tree) AddRouter(pattern string, runObject interface{}) {
  193. t.addseg(splitPath(pattern), runObject, nil, "")
  194. }
  195. // "/"
  196. // "admin" ->
  197. func (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) {
  198. if len(segments) == 0 {
  199. if reg != "" {
  200. t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile("^" + reg + "$")})
  201. } else {
  202. t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards})
  203. }
  204. } else {
  205. seg := segments[0]
  206. iswild, params, regexpStr := splitSegment(seg)
  207. // if it's ? meaning can igone this, so add one more rule for it
  208. if len(params) > 0 && params[0] == ":" {
  209. t.addseg(segments[1:], route, wildcards, reg)
  210. params = params[1:]
  211. }
  212. //Rule: /login/*/access match /login/2009/11/access
  213. //if already has *, and when loop the access, should as a regexpStr
  214. if !iswild && utils.InSlice(":splat", wildcards) {
  215. iswild = true
  216. regexpStr = seg
  217. }
  218. //Rule: /user/:id/*
  219. if seg == "*" && len(wildcards) > 0 && reg == "" {
  220. regexpStr = "(.+)"
  221. }
  222. if iswild {
  223. if t.wildcard == nil {
  224. t.wildcard = NewTree()
  225. }
  226. if regexpStr != "" {
  227. if reg == "" {
  228. rr := ""
  229. for _, w := range wildcards {
  230. if w == ":splat" {
  231. rr = rr + "(.+)/"
  232. } else {
  233. rr = rr + "([^/]+)/"
  234. }
  235. }
  236. regexpStr = rr + regexpStr
  237. } else {
  238. regexpStr = "/" + regexpStr
  239. }
  240. } else if reg != "" {
  241. if seg == "*.*" {
  242. regexpStr = "/([^.]+).(.+)"
  243. params = params[1:]
  244. } else {
  245. for range params {
  246. regexpStr = "/([^/]+)" + regexpStr
  247. }
  248. }
  249. } else {
  250. if seg == "*.*" {
  251. params = params[1:]
  252. }
  253. }
  254. t.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr)
  255. } else {
  256. var subTree *Tree
  257. for _, sub := range t.fixrouters {
  258. if sub.prefix == seg {
  259. subTree = sub
  260. break
  261. }
  262. }
  263. if subTree == nil {
  264. subTree = NewTree()
  265. subTree.prefix = seg
  266. t.fixrouters = append(t.fixrouters, subTree)
  267. }
  268. subTree.addseg(segments[1:], route, wildcards, reg)
  269. }
  270. }
  271. }
  272. // Match router to runObject & params
  273. func (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{}) {
  274. if len(pattern) == 0 || pattern[0] != '/' {
  275. return nil
  276. }
  277. w := make([]string, 0, 20)
  278. return t.match(pattern[1:], pattern, w, ctx)
  279. }
  280. func (t *Tree) match(treePattern string, pattern string, wildcardValues []string, ctx *context.Context) (runObject interface{}) {
  281. if len(pattern) > 0 {
  282. i := 0
  283. for ; i < len(pattern) && pattern[i] == '/'; i++ {
  284. }
  285. pattern = pattern[i:]
  286. }
  287. // Handle leaf nodes:
  288. if len(pattern) == 0 {
  289. for _, l := range t.leaves {
  290. if ok := l.match(treePattern, wildcardValues, ctx); ok {
  291. return l.runObject
  292. }
  293. }
  294. if t.wildcard != nil {
  295. for _, l := range t.wildcard.leaves {
  296. if ok := l.match(treePattern, wildcardValues, ctx); ok {
  297. return l.runObject
  298. }
  299. }
  300. }
  301. return nil
  302. }
  303. var seg string
  304. i, l := 0, len(pattern)
  305. for ; i < l && pattern[i] != '/'; i++ {
  306. }
  307. if i == 0 {
  308. seg = pattern
  309. pattern = ""
  310. } else {
  311. seg = pattern[:i]
  312. pattern = pattern[i:]
  313. }
  314. for _, subTree := range t.fixrouters {
  315. if subTree.prefix == seg {
  316. if len(pattern) != 0 && pattern[0] == '/' {
  317. treePattern = pattern[1:]
  318. } else {
  319. treePattern = pattern
  320. }
  321. runObject = subTree.match(treePattern, pattern, wildcardValues, ctx)
  322. if runObject != nil {
  323. break
  324. }
  325. }
  326. }
  327. if runObject == nil && len(t.fixrouters) > 0 {
  328. // Filter the .json .xml .html extension
  329. for _, str := range allowSuffixExt {
  330. if strings.HasSuffix(seg, str) {
  331. for _, subTree := range t.fixrouters {
  332. if subTree.prefix == seg[:len(seg)-len(str)] {
  333. runObject = subTree.match(treePattern, pattern, wildcardValues, ctx)
  334. if runObject != nil {
  335. ctx.Input.SetParam(":ext", str[1:])
  336. }
  337. }
  338. }
  339. }
  340. }
  341. }
  342. if runObject == nil && t.wildcard != nil {
  343. runObject = t.wildcard.match(treePattern, pattern, append(wildcardValues, seg), ctx)
  344. }
  345. if runObject == nil && len(t.leaves) > 0 {
  346. wildcardValues = append(wildcardValues, seg)
  347. start, i := 0, 0
  348. for ; i < len(pattern); i++ {
  349. if pattern[i] == '/' {
  350. if i != 0 && start < len(pattern) {
  351. wildcardValues = append(wildcardValues, pattern[start:i])
  352. }
  353. start = i + 1
  354. continue
  355. }
  356. }
  357. if start > 0 {
  358. wildcardValues = append(wildcardValues, pattern[start:i])
  359. }
  360. for _, l := range t.leaves {
  361. if ok := l.match(treePattern, wildcardValues, ctx); ok {
  362. return l.runObject
  363. }
  364. }
  365. }
  366. return runObject
  367. }
  368. type leafInfo struct {
  369. // names of wildcards that lead to this leaf. eg, ["id" "name"] for the wildcard ":id" and ":name"
  370. wildcards []string
  371. // if the leaf is regexp
  372. regexps *regexp.Regexp
  373. runObject interface{}
  374. }
  375. func (leaf *leafInfo) match(treePattern string, wildcardValues []string, ctx *context.Context) (ok bool) {
  376. //fmt.Println("Leaf:", wildcardValues, leaf.wildcards, leaf.regexps)
  377. if leaf.regexps == nil {
  378. if len(wildcardValues) == 0 && len(leaf.wildcards) == 0 { // static path
  379. return true
  380. }
  381. // match *
  382. if len(leaf.wildcards) == 1 && leaf.wildcards[0] == ":splat" {
  383. ctx.Input.SetParam(":splat", treePattern)
  384. return true
  385. }
  386. // match *.* or :id
  387. if len(leaf.wildcards) >= 2 && leaf.wildcards[len(leaf.wildcards)-2] == ":path" && leaf.wildcards[len(leaf.wildcards)-1] == ":ext" {
  388. if len(leaf.wildcards) == 2 {
  389. lastone := wildcardValues[len(wildcardValues)-1]
  390. strs := strings.SplitN(lastone, ".", 2)
  391. if len(strs) == 2 {
  392. ctx.Input.SetParam(":ext", strs[1])
  393. }
  394. ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[:len(wildcardValues)-1]...), strs[0]))
  395. return true
  396. } else if len(wildcardValues) < 2 {
  397. return false
  398. }
  399. var index int
  400. for index = 0; index < len(leaf.wildcards)-2; index++ {
  401. ctx.Input.SetParam(leaf.wildcards[index], wildcardValues[index])
  402. }
  403. lastone := wildcardValues[len(wildcardValues)-1]
  404. strs := strings.SplitN(lastone, ".", 2)
  405. if len(strs) == 2 {
  406. ctx.Input.SetParam(":ext", strs[1])
  407. }
  408. if index > (len(wildcardValues) - 1) {
  409. ctx.Input.SetParam(":path", "")
  410. } else {
  411. ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[index:len(wildcardValues)-1]...), strs[0]))
  412. }
  413. return true
  414. }
  415. // match :id
  416. if len(leaf.wildcards) != len(wildcardValues) {
  417. return false
  418. }
  419. for j, v := range leaf.wildcards {
  420. ctx.Input.SetParam(v, wildcardValues[j])
  421. }
  422. return true
  423. }
  424. if !leaf.regexps.MatchString(path.Join(wildcardValues...)) {
  425. return false
  426. }
  427. matches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...))
  428. for i, match := range matches[1:] {
  429. if i < len(leaf.wildcards) {
  430. ctx.Input.SetParam(leaf.wildcards[i], match)
  431. }
  432. }
  433. return true
  434. }
  435. // "/" -> []
  436. // "/admin" -> ["admin"]
  437. // "/admin/" -> ["admin"]
  438. // "/admin/users" -> ["admin", "users"]
  439. func splitPath(key string) []string {
  440. key = strings.Trim(key, "/ ")
  441. if key == "" {
  442. return []string{}
  443. }
  444. return strings.Split(key, "/")
  445. }
  446. // "admin" -> false, nil, ""
  447. // ":id" -> true, [:id], ""
  448. // "?:id" -> true, [: :id], "" : meaning can empty
  449. // ":id:int" -> true, [:id], ([0-9]+)
  450. // ":name:string" -> true, [:name], ([\w]+)
  451. // ":id([0-9]+)" -> true, [:id], ([0-9]+)
  452. // ":id([0-9]+)_:name" -> true, [:id :name], ([0-9]+)_(.+)
  453. // "cms_:id_:page.html" -> true, [:id_ :page], cms_(.+)(.+).html
  454. // "cms_:id(.+)_:page.html" -> true, [:id :page], cms_(.+)_(.+).html
  455. // "*" -> true, [:splat], ""
  456. // "*.*" -> true,[. :path :ext], "" . meaning separator
  457. func splitSegment(key string) (bool, []string, string) {
  458. if strings.HasPrefix(key, "*") {
  459. if key == "*.*" {
  460. return true, []string{".", ":path", ":ext"}, ""
  461. }
  462. return true, []string{":splat"}, ""
  463. }
  464. if strings.ContainsAny(key, ":") {
  465. var paramsNum int
  466. var out []rune
  467. var start bool
  468. var startexp bool
  469. var param []rune
  470. var expt []rune
  471. var skipnum int
  472. params := []string{}
  473. reg := regexp.MustCompile(`[a-zA-Z0-9_]+`)
  474. for i, v := range key {
  475. if skipnum > 0 {
  476. skipnum--
  477. continue
  478. }
  479. if start {
  480. //:id:int and :name:string
  481. if v == ':' {
  482. if len(key) >= i+4 {
  483. if key[i+1:i+4] == "int" {
  484. out = append(out, []rune("([0-9]+)")...)
  485. params = append(params, ":"+string(param))
  486. start = false
  487. startexp = false
  488. skipnum = 3
  489. param = make([]rune, 0)
  490. paramsNum++
  491. continue
  492. }
  493. }
  494. if len(key) >= i+7 {
  495. if key[i+1:i+7] == "string" {
  496. out = append(out, []rune(`([\w]+)`)...)
  497. params = append(params, ":"+string(param))
  498. paramsNum++
  499. start = false
  500. startexp = false
  501. skipnum = 6
  502. param = make([]rune, 0)
  503. continue
  504. }
  505. }
  506. }
  507. // params only support a-zA-Z0-9
  508. if reg.MatchString(string(v)) {
  509. param = append(param, v)
  510. continue
  511. }
  512. if v != '(' {
  513. out = append(out, []rune(`(.+)`)...)
  514. params = append(params, ":"+string(param))
  515. param = make([]rune, 0)
  516. paramsNum++
  517. start = false
  518. startexp = false
  519. }
  520. }
  521. if startexp {
  522. if v != ')' {
  523. expt = append(expt, v)
  524. continue
  525. }
  526. }
  527. // Escape Sequence '\'
  528. if i > 0 && key[i-1] == '\\' {
  529. out = append(out, v)
  530. } else if v == ':' {
  531. param = make([]rune, 0)
  532. start = true
  533. } else if v == '(' {
  534. startexp = true
  535. start = false
  536. if len(param) > 0 {
  537. params = append(params, ":"+string(param))
  538. param = make([]rune, 0)
  539. }
  540. paramsNum++
  541. expt = make([]rune, 0)
  542. expt = append(expt, '(')
  543. } else if v == ')' {
  544. startexp = false
  545. expt = append(expt, ')')
  546. out = append(out, expt...)
  547. param = make([]rune, 0)
  548. } else if v == '?' {
  549. params = append(params, ":")
  550. } else {
  551. out = append(out, v)
  552. }
  553. }
  554. if len(param) > 0 {
  555. if paramsNum > 0 {
  556. out = append(out, []rune(`(.+)`)...)
  557. }
  558. params = append(params, ":"+string(param))
  559. }
  560. return true, params, string(out)
  561. }
  562. return false, nil, ""
  563. }