github.com/kotovmak/go-admin@v1.1.1/context/trie.go (about) 1 // Copyright 2019 GoAdmin Core Team. All rights reserved. 2 // Use of this source code is governed by a Apache-2.0 style 3 // license that can be found in the LICENSE file. 4 5 package context 6 7 import "fmt" 8 9 type node struct { 10 children []*node 11 value string 12 method []string 13 handle [][]Handler 14 } 15 16 func tree() *node { 17 return &node{ 18 children: make([]*node, 0), 19 value: "/", 20 handle: nil, 21 } 22 } 23 24 func (n *node) hasMethod(method string) int { 25 for k, m := range n.method { 26 if m == method { 27 return k 28 } 29 } 30 return -1 31 } 32 33 func (n *node) addMethodAndHandler(method string, handler []Handler) { 34 n.method = append(n.method, method) 35 n.handle = append(n.handle, handler) 36 } 37 38 func (n *node) addChild(child *node) { 39 n.children = append(n.children, child) 40 } 41 42 func (n *node) addContent(value string) *node { 43 var child = n.search(value) 44 if child == nil { 45 child = &node{ 46 children: make([]*node, 0), 47 value: value, 48 } 49 n.addChild(child) 50 } 51 return child 52 } 53 54 func (n *node) search(value string) *node { 55 for _, child := range n.children { 56 if child.value == value || child.value == "*" { 57 return child 58 } 59 } 60 return nil 61 } 62 63 func (n *node) addPath(paths []string, method string, handler []Handler) { 64 child := n 65 for i := 0; i < len(paths); i++ { 66 child = child.addContent(paths[i]) 67 } 68 child.addMethodAndHandler(method, handler) 69 } 70 71 func (n *node) findPath(paths []string, method string) []Handler { 72 child := n 73 for i := 0; i < len(paths); i++ { 74 child = child.search(paths[i]) 75 if child == nil { 76 return nil 77 } 78 } 79 80 methodIndex := child.hasMethod(method) 81 if methodIndex == -1 { 82 return nil 83 } 84 85 return child.handle[methodIndex] 86 } 87 88 func (n *node) print() { 89 fmt.Println(n) 90 } 91 92 func (n *node) printChildren() { 93 n.print() 94 for _, child := range n.children { 95 child.printChildren() 96 } 97 } 98 99 func stringToArr(path string) []string { 100 var ( 101 paths = make([]string, 0) 102 start = 0 103 end int 104 isWildcard = false 105 ) 106 for i := 0; i < len(path); i++ { 107 if i == 0 && path[0] == '/' { 108 start = 1 109 continue 110 } 111 if path[i] == ':' { 112 isWildcard = true 113 } 114 if i == len(path)-1 { 115 end = i + 1 116 if isWildcard { 117 paths = append(paths, "*") 118 } else { 119 paths = append(paths, path[start:end]) 120 } 121 } 122 if path[i] == '/' { 123 end = i 124 if isWildcard { 125 paths = append(paths, "*") 126 } else { 127 paths = append(paths, path[start:end]) 128 } 129 start = i + 1 130 isWildcard = false 131 } 132 } 133 return paths 134 }