router.go 8.5 KB

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