router.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package tango
  2. import (
  3. "reflect"
  4. "regexp"
  5. "strings"
  6. "net/url"
  7. "fmt"
  8. "net/http"
  9. )
  10. type RouteType int
  11. const (
  12. FuncRoute RouteType = iota + 1 // func ()
  13. FuncHttpRoute // func (http.ResponseWriter, *http.Request)
  14. FuncReqRoute // func (*http.Request)
  15. FuncResponseRoute // func (http.ResponseWriter)
  16. FuncCtxRoute // func (*tango.Context)
  17. StructRoute // func (st) Get()
  18. StructPtrRoute // func (*struct) Get()
  19. )
  20. type PathType int
  21. const (
  22. StaticPath PathType = iota + 1
  23. NamedPath
  24. RegexpPath
  25. )
  26. var (
  27. SupportMethods = []string{
  28. "GET",
  29. "POST",
  30. "HEAD",
  31. "DELETE",
  32. "PUT",
  33. "OPTIONS",
  34. "TRACE",
  35. "PATCH",
  36. }
  37. PoolSize = 800
  38. )
  39. // Route
  40. type Route struct {
  41. path string //path string
  42. regexp *regexp.Regexp //path regexp
  43. pathType PathType
  44. method reflect.Value
  45. routeType RouteType
  46. pool *pool
  47. }
  48. func NewRoute(r string, t reflect.Type,
  49. method reflect.Value, tp RouteType) *Route {
  50. var pathType = StaticPath
  51. var cr *regexp.Regexp
  52. var err error
  53. if regexp.QuoteMeta(r) != r {
  54. pathType = RegexpPath
  55. cr, err = regexp.Compile(r)
  56. if err != nil {
  57. panic("wrong route:"+err.Error())
  58. return nil
  59. }
  60. } else if strings.Contains(r, ":") {
  61. pathType = NamedPath
  62. }
  63. return &Route{
  64. path: r,
  65. regexp: cr,
  66. pathType: pathType,
  67. method: method,
  68. routeType: tp,
  69. pool: newPool(PoolSize, t),
  70. }
  71. }
  72. func (r *Route) Method() reflect.Value {
  73. return r.method
  74. }
  75. func (r *Route) PathType() PathType {
  76. return r.pathType
  77. }
  78. func (r *Route) RouteType() RouteType {
  79. return r.routeType
  80. }
  81. func (r *Route) IsStruct() bool {
  82. return r.routeType == StructRoute || r.routeType == StructPtrRoute
  83. }
  84. func (r *Route) newAction() reflect.Value {
  85. if !r.IsStruct() {
  86. return r.method
  87. }
  88. return r.pool.New()
  89. }
  90. func (r *Route) try(path string) (url.Values, bool) {
  91. p := make(url.Values)
  92. var i, j int
  93. for i < len(path) {
  94. switch {
  95. case j >= len(r.path):
  96. if r.path != "/" && len(r.path) > 0 && r.path[len(r.path)-1] == '/' {
  97. return p, true
  98. }
  99. return nil, false
  100. case r.path[j] == ':':
  101. var name, val string
  102. var nextc byte
  103. name, nextc, j = match(r.path, isAlnum, j+1)
  104. val, _, i = match(path, matchPart(nextc), i)
  105. p.Add(":"+name, val)
  106. case path[i] == r.path[j]:
  107. i++
  108. j++
  109. default:
  110. return nil, false
  111. }
  112. }
  113. if j != len(r.path) {
  114. return nil, false
  115. }
  116. return p, true
  117. }
  118. type Router interface {
  119. Route(methods []string, path string, handler interface{})
  120. Match(requestPath, method string) (*Route, url.Values)
  121. }
  122. type router struct {
  123. routes map[string][]*Route
  124. routesEq map[string]map[string]*Route
  125. routesName map[string][]*Route
  126. }
  127. func NewRouter() Router {
  128. routesEq := make(map[string]map[string]*Route)
  129. for _, m := range SupportMethods {
  130. routesEq[m] = make(map[string]*Route)
  131. }
  132. routesName := make(map[string][]*Route)
  133. for _, m := range SupportMethods {
  134. routesName[m] = make([]*Route, 0)
  135. }
  136. routes := make(map[string][]*Route)
  137. for _, m := range SupportMethods {
  138. routes[m] = make([]*Route, 0)
  139. }
  140. return &router{
  141. routesEq: routesEq,
  142. routes: routes,
  143. routesName: routesName,
  144. }
  145. }
  146. func matchPart(b byte) func(byte) bool {
  147. return func(c byte) bool {
  148. return c != b && c != '/'
  149. }
  150. }
  151. func match(s string, f func(byte) bool, i int) (matched string, next byte, j int) {
  152. j = i
  153. for j < len(s) && f(s[j]) {
  154. j++
  155. }
  156. if j < len(s) {
  157. next = s[j]
  158. }
  159. return s[i:j], next, j
  160. }
  161. func isAlpha(ch byte) bool {
  162. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'
  163. }
  164. func isDigit(ch byte) bool {
  165. return '0' <= ch && ch <= '9'
  166. }
  167. func isAlnum(ch byte) bool {
  168. return isAlpha(ch) || isDigit(ch)
  169. }
  170. func tail(pat, path string) string {
  171. var i, j int
  172. for i < len(path) {
  173. switch {
  174. case j >= len(pat):
  175. if pat[len(pat)-1] == '/' {
  176. return path[i:]
  177. }
  178. return ""
  179. case pat[j] == ':':
  180. var nextc byte
  181. _, nextc, j = match(pat, isAlnum, j+1)
  182. _, _, i = match(path, matchPart(nextc), i)
  183. case path[i] == pat[j]:
  184. i++
  185. j++
  186. default:
  187. return ""
  188. }
  189. }
  190. return ""
  191. }
  192. func removeStick(uri string) string {
  193. uri = strings.TrimRight(uri, "/")
  194. if uri == "" {
  195. uri = "/"
  196. }
  197. return uri
  198. }
  199. func (router *router) Route(methods []string, url string, c interface{}) {
  200. vc := reflect.ValueOf(c)
  201. if vc.Kind() == reflect.Func {
  202. router.addFunc(methods, url, c)
  203. } else if vc.Kind() == reflect.Ptr && vc.Elem().Kind() == reflect.Struct {
  204. router.addStruct(methods, url, c)
  205. }
  206. }
  207. func (router *router) addRoute(m string, route *Route) {
  208. switch route.pathType {
  209. case StaticPath:
  210. router.routesEq[m][route.path] = route
  211. case NamedPath:
  212. router.routesName[m] = append(router.routesName[m], route)
  213. case RegexpPath:
  214. router.routes[m] = append(router.routes[m], route)
  215. }
  216. }
  217. /*
  218. Tango supports 5 form funcs
  219. func()
  220. func(*Context)
  221. func(http.ResponseWriter, *http.Request)
  222. func(http.ResponseWriter)
  223. func(*http.Request)
  224. it can has or has not return value
  225. */
  226. func (router *router) addFunc(methods []string, url string, c interface{}) {
  227. vc := reflect.ValueOf(c)
  228. t := vc.Type()
  229. var r *Route
  230. if t.NumIn() == 0 {
  231. r = NewRoute(removeStick(url), t, vc, FuncRoute)
  232. } else if t.NumIn() == 1 {
  233. if t.In(0) == reflect.TypeOf(new(Context)) {
  234. r = NewRoute(removeStick(url), t, vc, FuncCtxRoute)
  235. } else if t.In(0) == reflect.TypeOf(new(http.Request)) {
  236. r = NewRoute(removeStick(url), t, vc, FuncReqRoute)
  237. } else if t.In(0).Kind() == reflect.Interface && t.In(0).Name() == "ResponseWriter" &&
  238. t.In(0).PkgPath() == "net/http" {
  239. r = NewRoute(removeStick(url), t, vc, FuncResponseRoute)
  240. } else {
  241. panic("no support function type")
  242. }
  243. } else if t.NumIn() == 2 &&
  244. (t.In(0).Kind() == reflect.Interface && t.In(0).Name() == "ResponseWriter" &&
  245. t.In(0).PkgPath() == "net/http") &&
  246. t.In(1) == reflect.TypeOf(new(http.Request)) {
  247. r = NewRoute(removeStick(url), t, vc, FuncHttpRoute)
  248. } else {
  249. panic("no support function type")
  250. }
  251. for _, m := range methods {
  252. router.addRoute(m, r)
  253. }
  254. }
  255. func (router *router) addStruct(methods []string, url string, c interface{}) {
  256. vc := reflect.ValueOf(c)
  257. t := vc.Type().Elem()
  258. // added a default method Get, Post
  259. for _, name := range methods {
  260. newName := strings.Title(strings.ToLower(name))
  261. if m, ok := t.MethodByName(newName); ok {
  262. router.addRoute(name, NewRoute(removeStick(url), t, m.Func, StructPtrRoute))
  263. } else if m, ok := vc.Type().MethodByName(newName); ok {
  264. router.addRoute(name, NewRoute(removeStick(url), t, m.Func, StructRoute))
  265. }
  266. }
  267. }
  268. // when a request ask, then match the correct route
  269. func (router *router) Match(reqPath, allowMethod string) (*Route, url.Values) {
  270. // for non-regular path, search the map
  271. if routes, ok := router.routesEq[allowMethod]; ok {
  272. if route, ok := routes[reqPath]; ok {
  273. return route, make(url.Values)
  274. }
  275. }
  276. // name match
  277. routes := router.routesName[allowMethod]
  278. for _, r := range routes {
  279. if args, ok := r.try(reqPath); ok {
  280. return r, args
  281. }
  282. }
  283. // regex match
  284. routes = router.routes[allowMethod]
  285. for _, r := range routes {
  286. if !r.regexp.MatchString(reqPath) {
  287. continue
  288. }
  289. match := r.regexp.FindStringSubmatch(reqPath)
  290. if len(match[0]) != len(reqPath) {
  291. continue
  292. }
  293. var args = make(url.Values)
  294. // for regexp :0 -> first match param :1 -> the second
  295. for i, arg := range match[1:] {
  296. args.Add(fmt.Sprintf(":%d", i), arg)
  297. }
  298. return r, args
  299. }
  300. return nil, nil
  301. }