You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2847 lines
88 KiB

  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mux
  5. import (
  6. "bufio"
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "testing"
  15. )
  16. func (r *Route) GoString() string {
  17. matchers := make([]string, len(r.matchers))
  18. for i, m := range r.matchers {
  19. matchers[i] = fmt.Sprintf("%#v", m)
  20. }
  21. return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", "))
  22. }
  23. func (r *routeRegexp) GoString() string {
  24. return fmt.Sprintf("&routeRegexp{template: %q, regexpType: %v, options: %v, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.regexpType, r.options, r.regexp.String(), r.reverse, r.varsN, r.varsR)
  25. }
  26. type routeTest struct {
  27. title string // title of the test
  28. route *Route // the route being tested
  29. request *http.Request // a request to test the route
  30. vars map[string]string // the expected vars of the match
  31. scheme string // the expected scheme of the built URL
  32. host string // the expected host of the built URL
  33. path string // the expected path of the built URL
  34. query string // the expected query string of the built URL
  35. pathTemplate string // the expected path template of the route
  36. hostTemplate string // the expected host template of the route
  37. queriesTemplate string // the expected query template of the route
  38. methods []string // the expected route methods
  39. pathRegexp string // the expected path regexp
  40. queriesRegexp string // the expected query regexp
  41. shouldMatch bool // whether the request is expected to match the route at all
  42. shouldRedirect bool // whether the request should result in a redirect
  43. }
  44. func TestHost(t *testing.T) {
  45. tests := []routeTest{
  46. {
  47. title: "Host route match",
  48. route: new(Route).Host("aaa.bbb.ccc"),
  49. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  50. vars: map[string]string{},
  51. host: "aaa.bbb.ccc",
  52. path: "",
  53. shouldMatch: true,
  54. },
  55. {
  56. title: "Host route, wrong host in request URL",
  57. route: new(Route).Host("aaa.bbb.ccc"),
  58. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  59. vars: map[string]string{},
  60. host: "aaa.bbb.ccc",
  61. path: "",
  62. shouldMatch: false,
  63. },
  64. {
  65. title: "Host route with port, match",
  66. route: new(Route).Host("aaa.bbb.ccc:1234"),
  67. request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"),
  68. vars: map[string]string{},
  69. host: "aaa.bbb.ccc:1234",
  70. path: "",
  71. shouldMatch: true,
  72. },
  73. {
  74. title: "Host route with port, wrong port in request URL",
  75. route: new(Route).Host("aaa.bbb.ccc:1234"),
  76. request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"),
  77. vars: map[string]string{},
  78. host: "aaa.bbb.ccc:1234",
  79. path: "",
  80. shouldMatch: false,
  81. },
  82. {
  83. title: "Host route, match with host in request header",
  84. route: new(Route).Host("aaa.bbb.ccc"),
  85. request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"),
  86. vars: map[string]string{},
  87. host: "aaa.bbb.ccc",
  88. path: "",
  89. shouldMatch: true,
  90. },
  91. {
  92. title: "Host route, wrong host in request header",
  93. route: new(Route).Host("aaa.bbb.ccc"),
  94. request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"),
  95. vars: map[string]string{},
  96. host: "aaa.bbb.ccc",
  97. path: "",
  98. shouldMatch: false,
  99. },
  100. {
  101. title: "Host route with port, match with request header",
  102. route: new(Route).Host("aaa.bbb.ccc:1234"),
  103. request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"),
  104. vars: map[string]string{},
  105. host: "aaa.bbb.ccc:1234",
  106. path: "",
  107. shouldMatch: true,
  108. },
  109. {
  110. title: "Host route with port, wrong host in request header",
  111. route: new(Route).Host("aaa.bbb.ccc:1234"),
  112. request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"),
  113. vars: map[string]string{},
  114. host: "aaa.bbb.ccc:1234",
  115. path: "",
  116. shouldMatch: false,
  117. },
  118. {
  119. title: "Host route with pattern, match with request header",
  120. route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc:1{v2:(?:23|4)}"),
  121. request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:123"),
  122. vars: map[string]string{"v1": "bbb", "v2": "23"},
  123. host: "aaa.bbb.ccc:123",
  124. path: "",
  125. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc:1{v2:(?:23|4)}`,
  126. shouldMatch: true,
  127. },
  128. {
  129. title: "Host route with pattern, match",
  130. route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
  131. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  132. vars: map[string]string{"v1": "bbb"},
  133. host: "aaa.bbb.ccc",
  134. path: "",
  135. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
  136. shouldMatch: true,
  137. },
  138. {
  139. title: "Host route with pattern, additional capturing group, match",
  140. route: new(Route).Host("aaa.{v1:[a-z]{2}(?:b|c)}.ccc"),
  141. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  142. vars: map[string]string{"v1": "bbb"},
  143. host: "aaa.bbb.ccc",
  144. path: "",
  145. hostTemplate: `aaa.{v1:[a-z]{2}(?:b|c)}.ccc`,
  146. shouldMatch: true,
  147. },
  148. {
  149. title: "Host route with pattern, wrong host in request URL",
  150. route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
  151. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  152. vars: map[string]string{"v1": "bbb"},
  153. host: "aaa.bbb.ccc",
  154. path: "",
  155. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
  156. shouldMatch: false,
  157. },
  158. {
  159. title: "Host route with multiple patterns, match",
  160. route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
  161. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  162. vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
  163. host: "aaa.bbb.ccc",
  164. path: "",
  165. hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
  166. shouldMatch: true,
  167. },
  168. {
  169. title: "Host route with multiple patterns, wrong host in request URL",
  170. route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
  171. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  172. vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
  173. host: "aaa.bbb.ccc",
  174. path: "",
  175. hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
  176. shouldMatch: false,
  177. },
  178. {
  179. title: "Host route with hyphenated name and pattern, match",
  180. route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"),
  181. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  182. vars: map[string]string{"v-1": "bbb"},
  183. host: "aaa.bbb.ccc",
  184. path: "",
  185. hostTemplate: `aaa.{v-1:[a-z]{3}}.ccc`,
  186. shouldMatch: true,
  187. },
  188. {
  189. title: "Host route with hyphenated name and pattern, additional capturing group, match",
  190. route: new(Route).Host("aaa.{v-1:[a-z]{2}(?:b|c)}.ccc"),
  191. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  192. vars: map[string]string{"v-1": "bbb"},
  193. host: "aaa.bbb.ccc",
  194. path: "",
  195. hostTemplate: `aaa.{v-1:[a-z]{2}(?:b|c)}.ccc`,
  196. shouldMatch: true,
  197. },
  198. {
  199. title: "Host route with multiple hyphenated names and patterns, match",
  200. route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"),
  201. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  202. vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"},
  203. host: "aaa.bbb.ccc",
  204. path: "",
  205. hostTemplate: `{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}`,
  206. shouldMatch: true,
  207. },
  208. }
  209. for _, test := range tests {
  210. t.Run(test.title, func(t *testing.T) {
  211. testRoute(t, test)
  212. testTemplate(t, test)
  213. })
  214. }
  215. }
  216. func TestPath(t *testing.T) {
  217. tests := []routeTest{
  218. {
  219. title: "Path route, match",
  220. route: new(Route).Path("/111/222/333"),
  221. request: newRequest("GET", "http://localhost/111/222/333"),
  222. vars: map[string]string{},
  223. host: "",
  224. path: "/111/222/333",
  225. shouldMatch: true,
  226. },
  227. {
  228. title: "Path route, match with trailing slash in request and path",
  229. route: new(Route).Path("/111/"),
  230. request: newRequest("GET", "http://localhost/111/"),
  231. vars: map[string]string{},
  232. host: "",
  233. path: "/111/",
  234. shouldMatch: true,
  235. },
  236. {
  237. title: "Path route, do not match with trailing slash in path",
  238. route: new(Route).Path("/111/"),
  239. request: newRequest("GET", "http://localhost/111"),
  240. vars: map[string]string{},
  241. host: "",
  242. path: "/111",
  243. pathTemplate: `/111/`,
  244. pathRegexp: `^/111/$`,
  245. shouldMatch: false,
  246. },
  247. {
  248. title: "Path route, do not match with trailing slash in request",
  249. route: new(Route).Path("/111"),
  250. request: newRequest("GET", "http://localhost/111/"),
  251. vars: map[string]string{},
  252. host: "",
  253. path: "/111/",
  254. pathTemplate: `/111`,
  255. shouldMatch: false,
  256. },
  257. {
  258. title: "Path route, match root with no host",
  259. route: new(Route).Path("/"),
  260. request: newRequest("GET", "/"),
  261. vars: map[string]string{},
  262. host: "",
  263. path: "/",
  264. pathTemplate: `/`,
  265. pathRegexp: `^/$`,
  266. shouldMatch: true,
  267. },
  268. {
  269. title: "Path route, match root with no host, App Engine format",
  270. route: new(Route).Path("/"),
  271. request: func() *http.Request {
  272. r := newRequest("GET", "http://localhost/")
  273. r.RequestURI = "/"
  274. return r
  275. }(),
  276. vars: map[string]string{},
  277. host: "",
  278. path: "/",
  279. pathTemplate: `/`,
  280. shouldMatch: true,
  281. },
  282. {
  283. title: "Path route, wrong path in request in request URL",
  284. route: new(Route).Path("/111/222/333"),
  285. request: newRequest("GET", "http://localhost/1/2/3"),
  286. vars: map[string]string{},
  287. host: "",
  288. path: "/111/222/333",
  289. shouldMatch: false,
  290. },
  291. {
  292. title: "Path route with pattern, match",
  293. route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
  294. request: newRequest("GET", "http://localhost/111/222/333"),
  295. vars: map[string]string{"v1": "222"},
  296. host: "",
  297. path: "/111/222/333",
  298. pathTemplate: `/111/{v1:[0-9]{3}}/333`,
  299. shouldMatch: true,
  300. },
  301. {
  302. title: "Path route with pattern, URL in request does not match",
  303. route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
  304. request: newRequest("GET", "http://localhost/111/aaa/333"),
  305. vars: map[string]string{"v1": "222"},
  306. host: "",
  307. path: "/111/222/333",
  308. pathTemplate: `/111/{v1:[0-9]{3}}/333`,
  309. pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`,
  310. shouldMatch: false,
  311. },
  312. {
  313. title: "Path route with multiple patterns, match",
  314. route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
  315. request: newRequest("GET", "http://localhost/111/222/333"),
  316. vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
  317. host: "",
  318. path: "/111/222/333",
  319. pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
  320. pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
  321. shouldMatch: true,
  322. },
  323. {
  324. title: "Path route with multiple patterns, URL in request does not match",
  325. route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
  326. request: newRequest("GET", "http://localhost/111/aaa/333"),
  327. vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
  328. host: "",
  329. path: "/111/222/333",
  330. pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
  331. pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
  332. shouldMatch: false,
  333. },
  334. {
  335. title: "Path route with multiple patterns with pipe, match",
  336. route: new(Route).Path("/{category:a|(?:b/c)}/{product}/{id:[0-9]+}"),
  337. request: newRequest("GET", "http://localhost/a/product_name/1"),
  338. vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
  339. host: "",
  340. path: "/a/product_name/1",
  341. pathTemplate: `/{category:a|(?:b/c)}/{product}/{id:[0-9]+}`,
  342. pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`,
  343. shouldMatch: true,
  344. },
  345. {
  346. title: "Path route with hyphenated name and pattern, match",
  347. route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"),
  348. request: newRequest("GET", "http://localhost/111/222/333"),
  349. vars: map[string]string{"v-1": "222"},
  350. host: "",
  351. path: "/111/222/333",
  352. pathTemplate: `/111/{v-1:[0-9]{3}}/333`,
  353. pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`,
  354. shouldMatch: true,
  355. },
  356. {
  357. title: "Path route with multiple hyphenated names and patterns, match",
  358. route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"),
  359. request: newRequest("GET", "http://localhost/111/222/333"),
  360. vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"},
  361. host: "",
  362. path: "/111/222/333",
  363. pathTemplate: `/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}`,
  364. pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
  365. shouldMatch: true,
  366. },
  367. {
  368. title: "Path route with multiple hyphenated names and patterns with pipe, match",
  369. route: new(Route).Path("/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}"),
  370. request: newRequest("GET", "http://localhost/a/product_name/1"),
  371. vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"},
  372. host: "",
  373. path: "/a/product_name/1",
  374. pathTemplate: `/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}`,
  375. pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`,
  376. shouldMatch: true,
  377. },
  378. {
  379. title: "Path route with multiple hyphenated names and patterns with pipe and case insensitive, match",
  380. route: new(Route).Path("/{type:(?i:daily|mini|variety)}-{date:\\d{4,4}-\\d{2,2}-\\d{2,2}}"),
  381. request: newRequest("GET", "http://localhost/daily-2016-01-01"),
  382. vars: map[string]string{"type": "daily", "date": "2016-01-01"},
  383. host: "",
  384. path: "/daily-2016-01-01",
  385. pathTemplate: `/{type:(?i:daily|mini|variety)}-{date:\d{4,4}-\d{2,2}-\d{2,2}}`,
  386. pathRegexp: `^/(?P<v0>(?i:daily|mini|variety))-(?P<v1>\d{4,4}-\d{2,2}-\d{2,2})$`,
  387. shouldMatch: true,
  388. },
  389. {
  390. title: "Path route with empty match right after other match",
  391. route: new(Route).Path(`/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`),
  392. request: newRequest("GET", "http://localhost/111/222"),
  393. vars: map[string]string{"v1": "111", "v2": "", "v3": "222"},
  394. host: "",
  395. path: "/111/222",
  396. pathTemplate: `/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`,
  397. pathRegexp: `^/(?P<v0>[0-9]*)(?P<v1>[a-z]*)/(?P<v2>[0-9]*)$`,
  398. shouldMatch: true,
  399. },
  400. {
  401. title: "Path route with single pattern with pipe, match",
  402. route: new(Route).Path("/{category:a|b/c}"),
  403. request: newRequest("GET", "http://localhost/a"),
  404. vars: map[string]string{"category": "a"},
  405. host: "",
  406. path: "/a",
  407. pathTemplate: `/{category:a|b/c}`,
  408. shouldMatch: true,
  409. },
  410. {
  411. title: "Path route with single pattern with pipe, match",
  412. route: new(Route).Path("/{category:a|b/c}"),
  413. request: newRequest("GET", "http://localhost/b/c"),
  414. vars: map[string]string{"category": "b/c"},
  415. host: "",
  416. path: "/b/c",
  417. pathTemplate: `/{category:a|b/c}`,
  418. shouldMatch: true,
  419. },
  420. {
  421. title: "Path route with multiple patterns with pipe, match",
  422. route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
  423. request: newRequest("GET", "http://localhost/a/product_name/1"),
  424. vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
  425. host: "",
  426. path: "/a/product_name/1",
  427. pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
  428. shouldMatch: true,
  429. },
  430. {
  431. title: "Path route with multiple patterns with pipe, match",
  432. route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
  433. request: newRequest("GET", "http://localhost/b/c/product_name/1"),
  434. vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"},
  435. host: "",
  436. path: "/b/c/product_name/1",
  437. pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
  438. shouldMatch: true,
  439. },
  440. }
  441. for _, test := range tests {
  442. t.Run(test.title, func(t *testing.T) {
  443. testRoute(t, test)
  444. testTemplate(t, test)
  445. testUseEscapedRoute(t, test)
  446. testRegexp(t, test)
  447. })
  448. }
  449. }
  450. func TestPathPrefix(t *testing.T) {
  451. tests := []routeTest{
  452. {
  453. title: "PathPrefix route, match",
  454. route: new(Route).PathPrefix("/111"),
  455. request: newRequest("GET", "http://localhost/111/222/333"),
  456. vars: map[string]string{},
  457. host: "",
  458. path: "/111",
  459. shouldMatch: true,
  460. },
  461. {
  462. title: "PathPrefix route, match substring",
  463. route: new(Route).PathPrefix("/1"),
  464. request: newRequest("GET", "http://localhost/111/222/333"),
  465. vars: map[string]string{},
  466. host: "",
  467. path: "/1",
  468. shouldMatch: true,
  469. },
  470. {
  471. title: "PathPrefix route, URL prefix in request does not match",
  472. route: new(Route).PathPrefix("/111"),
  473. request: newRequest("GET", "http://localhost/1/2/3"),
  474. vars: map[string]string{},
  475. host: "",
  476. path: "/111",
  477. shouldMatch: false,
  478. },
  479. {
  480. title: "PathPrefix route with pattern, match",
  481. route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
  482. request: newRequest("GET", "http://localhost/111/222/333"),
  483. vars: map[string]string{"v1": "222"},
  484. host: "",
  485. path: "/111/222",
  486. pathTemplate: `/111/{v1:[0-9]{3}}`,
  487. shouldMatch: true,
  488. },
  489. {
  490. title: "PathPrefix route with pattern, URL prefix in request does not match",
  491. route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
  492. request: newRequest("GET", "http://localhost/111/aaa/333"),
  493. vars: map[string]string{"v1": "222"},
  494. host: "",
  495. path: "/111/222",
  496. pathTemplate: `/111/{v1:[0-9]{3}}`,
  497. shouldMatch: false,
  498. },
  499. {
  500. title: "PathPrefix route with multiple patterns, match",
  501. route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
  502. request: newRequest("GET", "http://localhost/111/222/333"),
  503. vars: map[string]string{"v1": "111", "v2": "222"},
  504. host: "",
  505. path: "/111/222",
  506. pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`,
  507. shouldMatch: true,
  508. },
  509. {
  510. title: "PathPrefix route with multiple patterns, URL prefix in request does not match",
  511. route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
  512. request: newRequest("GET", "http://localhost/111/aaa/333"),
  513. vars: map[string]string{"v1": "111", "v2": "222"},
  514. host: "",
  515. path: "/111/222",
  516. pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`,
  517. shouldMatch: false,
  518. },
  519. }
  520. for _, test := range tests {
  521. t.Run(test.title, func(t *testing.T) {
  522. testRoute(t, test)
  523. testTemplate(t, test)
  524. testUseEscapedRoute(t, test)
  525. })
  526. }
  527. }
  528. func TestSchemeHostPath(t *testing.T) {
  529. tests := []routeTest{
  530. {
  531. title: "Host and Path route, match",
  532. route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
  533. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  534. vars: map[string]string{},
  535. scheme: "http",
  536. host: "aaa.bbb.ccc",
  537. path: "/111/222/333",
  538. pathTemplate: `/111/222/333`,
  539. hostTemplate: `aaa.bbb.ccc`,
  540. shouldMatch: true,
  541. },
  542. {
  543. title: "Scheme, Host, and Path route, match",
  544. route: new(Route).Schemes("https").Host("aaa.bbb.ccc").Path("/111/222/333"),
  545. request: newRequest("GET", "https://aaa.bbb.ccc/111/222/333"),
  546. vars: map[string]string{},
  547. scheme: "https",
  548. host: "aaa.bbb.ccc",
  549. path: "/111/222/333",
  550. pathTemplate: `/111/222/333`,
  551. hostTemplate: `aaa.bbb.ccc`,
  552. shouldMatch: true,
  553. },
  554. {
  555. title: "Host and Path route, wrong host in request URL",
  556. route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
  557. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  558. vars: map[string]string{},
  559. scheme: "http",
  560. host: "aaa.bbb.ccc",
  561. path: "/111/222/333",
  562. pathTemplate: `/111/222/333`,
  563. hostTemplate: `aaa.bbb.ccc`,
  564. shouldMatch: false,
  565. },
  566. {
  567. title: "Host and Path route with pattern, match",
  568. route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
  569. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  570. vars: map[string]string{"v1": "bbb", "v2": "222"},
  571. scheme: "http",
  572. host: "aaa.bbb.ccc",
  573. path: "/111/222/333",
  574. pathTemplate: `/111/{v2:[0-9]{3}}/333`,
  575. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
  576. shouldMatch: true,
  577. },
  578. {
  579. title: "Scheme, Host, and Path route with host and path patterns, match",
  580. route: new(Route).Schemes("ftp", "ssss").Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
  581. request: newRequest("GET", "ssss://aaa.bbb.ccc/111/222/333"),
  582. vars: map[string]string{"v1": "bbb", "v2": "222"},
  583. scheme: "ftp",
  584. host: "aaa.bbb.ccc",
  585. path: "/111/222/333",
  586. pathTemplate: `/111/{v2:[0-9]{3}}/333`,
  587. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
  588. shouldMatch: true,
  589. },
  590. {
  591. title: "Host and Path route with pattern, URL in request does not match",
  592. route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
  593. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  594. vars: map[string]string{"v1": "bbb", "v2": "222"},
  595. scheme: "http",
  596. host: "aaa.bbb.ccc",
  597. path: "/111/222/333",
  598. pathTemplate: `/111/{v2:[0-9]{3}}/333`,
  599. hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
  600. shouldMatch: false,
  601. },
  602. {
  603. title: "Host and Path route with multiple patterns, match",
  604. route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
  605. request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
  606. vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
  607. scheme: "http",
  608. host: "aaa.bbb.ccc",
  609. path: "/111/222/333",
  610. pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
  611. hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
  612. shouldMatch: true,
  613. },
  614. {
  615. title: "Host and Path route with multiple patterns, URL in request does not match",
  616. route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
  617. request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
  618. vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
  619. scheme: "http",
  620. host: "aaa.bbb.ccc",
  621. path: "/111/222/333",
  622. pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
  623. hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
  624. shouldMatch: false,
  625. },
  626. }
  627. for _, test := range tests {
  628. t.Run(test.title, func(t *testing.T) {
  629. testRoute(t, test)
  630. testTemplate(t, test)
  631. testUseEscapedRoute(t, test)
  632. })
  633. }
  634. }
  635. func TestHeaders(t *testing.T) {
  636. // newRequestHeaders creates a new request with a method, url, and headers
  637. newRequestHeaders := func(method, url string, headers map[string]string) *http.Request {
  638. req, err := http.NewRequest(method, url, nil)
  639. if err != nil {
  640. panic(err)
  641. }
  642. for k, v := range headers {
  643. req.Header.Add(k, v)
  644. }
  645. return req
  646. }
  647. tests := []routeTest{
  648. {
  649. title: "Headers route, match",
  650. route: new(Route).Headers("foo", "bar", "baz", "ding"),
  651. request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}),
  652. vars: map[string]string{},
  653. host: "",
  654. path: "",
  655. shouldMatch: true,
  656. },
  657. {
  658. title: "Headers route, bad header values",
  659. route: new(Route).Headers("foo", "bar", "baz", "ding"),
  660. request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}),
  661. vars: map[string]string{},
  662. host: "",
  663. path: "",
  664. shouldMatch: false,
  665. },
  666. {
  667. title: "Headers route, regex header values to match",
  668. route: new(Route).Headers("foo", "ba[zr]"),
  669. request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}),
  670. vars: map[string]string{},
  671. host: "",
  672. path: "",
  673. shouldMatch: false,
  674. },
  675. {
  676. title: "Headers route, regex header values to match",
  677. route: new(Route).HeadersRegexp("foo", "ba[zr]"),
  678. request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}),
  679. vars: map[string]string{},
  680. host: "",
  681. path: "",
  682. shouldMatch: true,
  683. },
  684. }
  685. for _, test := range tests {
  686. t.Run(test.title, func(t *testing.T) {
  687. testRoute(t, test)
  688. testTemplate(t, test)
  689. })
  690. }
  691. }
  692. func TestMethods(t *testing.T) {
  693. tests := []routeTest{
  694. {
  695. title: "Methods route, match GET",
  696. route: new(Route).Methods("GET", "POST"),
  697. request: newRequest("GET", "http://localhost"),
  698. vars: map[string]string{},
  699. host: "",
  700. path: "",
  701. methods: []string{"GET", "POST"},
  702. shouldMatch: true,
  703. },
  704. {
  705. title: "Methods route, match POST",
  706. route: new(Route).Methods("GET", "POST"),
  707. request: newRequest("POST", "http://localhost"),
  708. vars: map[string]string{},
  709. host: "",
  710. path: "",
  711. methods: []string{"GET", "POST"},
  712. shouldMatch: true,
  713. },
  714. {
  715. title: "Methods route, bad method",
  716. route: new(Route).Methods("GET", "POST"),
  717. request: newRequest("PUT", "http://localhost"),
  718. vars: map[string]string{},
  719. host: "",
  720. path: "",
  721. methods: []string{"GET", "POST"},
  722. shouldMatch: false,
  723. },
  724. {
  725. title: "Route without methods",
  726. route: new(Route),
  727. request: newRequest("PUT", "http://localhost"),
  728. vars: map[string]string{},
  729. host: "",
  730. path: "",
  731. methods: []string{},
  732. shouldMatch: true,
  733. },
  734. }
  735. for _, test := range tests {
  736. t.Run(test.title, func(t *testing.T) {
  737. testRoute(t, test)
  738. testTemplate(t, test)
  739. testMethods(t, test)
  740. })
  741. }
  742. }
  743. func TestQueries(t *testing.T) {
  744. tests := []routeTest{
  745. {
  746. title: "Queries route, match",
  747. route: new(Route).Queries("foo", "bar", "baz", "ding"),
  748. request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
  749. vars: map[string]string{},
  750. host: "",
  751. path: "",
  752. query: "foo=bar&baz=ding",
  753. queriesTemplate: "foo=bar,baz=ding",
  754. queriesRegexp: "^foo=bar$,^baz=ding$",
  755. shouldMatch: true,
  756. },
  757. {
  758. title: "Queries route, match with a query string",
  759. route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
  760. request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"),
  761. vars: map[string]string{},
  762. host: "",
  763. path: "",
  764. query: "foo=bar&baz=ding",
  765. pathTemplate: `/api`,
  766. hostTemplate: `www.example.com`,
  767. queriesTemplate: "foo=bar,baz=ding",
  768. queriesRegexp: "^foo=bar$,^baz=ding$",
  769. shouldMatch: true,
  770. },
  771. {
  772. title: "Queries route, match with a query string out of order",
  773. route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
  774. request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"),
  775. vars: map[string]string{},
  776. host: "",
  777. path: "",
  778. query: "foo=bar&baz=ding",
  779. pathTemplate: `/api`,
  780. hostTemplate: `www.example.com`,
  781. queriesTemplate: "foo=bar,baz=ding",
  782. queriesRegexp: "^foo=bar$,^baz=ding$",
  783. shouldMatch: true,
  784. },
  785. {
  786. title: "Queries route, bad query",
  787. route: new(Route).Queries("foo", "bar", "baz", "ding"),
  788. request: newRequest("GET", "http://localhost?foo=bar&baz=dong"),
  789. vars: map[string]string{},
  790. host: "",
  791. path: "",
  792. queriesTemplate: "foo=bar,baz=ding",
  793. queriesRegexp: "^foo=bar$,^baz=ding$",
  794. shouldMatch: false,
  795. },
  796. {
  797. title: "Queries route with pattern, match",
  798. route: new(Route).Queries("foo", "{v1}"),
  799. request: newRequest("GET", "http://localhost?foo=bar"),
  800. vars: map[string]string{"v1": "bar"},
  801. host: "",
  802. path: "",
  803. query: "foo=bar",
  804. queriesTemplate: "foo={v1}",
  805. queriesRegexp: "^foo=(?P<v0>.*)$",
  806. shouldMatch: true,
  807. },
  808. {
  809. title: "Queries route with multiple patterns, match",
  810. route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"),
  811. request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
  812. vars: map[string]string{"v1": "bar", "v2": "ding"},
  813. host: "",
  814. path: "",
  815. query: "foo=bar&baz=ding",
  816. queriesTemplate: "foo={v1},baz={v2}",
  817. queriesRegexp: "^foo=(?P<v0>.*)$,^baz=(?P<v0>.*)$",
  818. shouldMatch: true,
  819. },
  820. {
  821. title: "Queries route with regexp pattern, match",
  822. route: new(Route).Queries("foo", "{v1:[0-9]+}"),
  823. request: newRequest("GET", "http://localhost?foo=10"),
  824. vars: map[string]string{"v1": "10"},
  825. host: "",
  826. path: "",
  827. query: "foo=10",
  828. queriesTemplate: "foo={v1:[0-9]+}",
  829. queriesRegexp: "^foo=(?P<v0>[0-9]+)$",
  830. shouldMatch: true,
  831. },
  832. {
  833. title: "Queries route with regexp pattern, regexp does not match",
  834. route: new(Route).Queries("foo", "{v1:[0-9]+}"),
  835. request: newRequest("GET", "http://localhost?foo=a"),
  836. vars: map[string]string{},
  837. host: "",
  838. path: "",
  839. queriesTemplate: "foo={v1:[0-9]+}",
  840. queriesRegexp: "^foo=(?P<v0>[0-9]+)$",
  841. shouldMatch: false,
  842. },
  843. {
  844. title: "Queries route with regexp pattern with quantifier, match",
  845. route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
  846. request: newRequest("GET", "http://localhost?foo=1"),
  847. vars: map[string]string{"v1": "1"},
  848. host: "",
  849. path: "",
  850. query: "foo=1",
  851. queriesTemplate: "foo={v1:[0-9]{1}}",
  852. queriesRegexp: "^foo=(?P<v0>[0-9]{1})$",
  853. shouldMatch: true,
  854. },
  855. {
  856. title: "Queries route with regexp pattern with quantifier, additional variable in query string, match",
  857. route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
  858. request: newRequest("GET", "http://localhost?bar=2&foo=1"),
  859. vars: map[string]string{"v1": "1"},
  860. host: "",
  861. path: "",
  862. query: "foo=1",
  863. queriesTemplate: "foo={v1:[0-9]{1}}",
  864. queriesRegexp: "^foo=(?P<v0>[0-9]{1})$",
  865. shouldMatch: true,
  866. },
  867. {
  868. title: "Queries route with regexp pattern with quantifier, regexp does not match",
  869. route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
  870. request: newRequest("GET", "http://localhost?foo=12"),
  871. vars: map[string]string{},
  872. host: "",
  873. path: "",
  874. queriesTemplate: "foo={v1:[0-9]{1}}",
  875. queriesRegexp: "^foo=(?P<v0>[0-9]{1})$",
  876. shouldMatch: false,
  877. },
  878. {
  879. title: "Queries route with regexp pattern with quantifier, additional capturing group",
  880. route: new(Route).Queries("foo", "{v1:[0-9]{1}(?:a|b)}"),
  881. request: newRequest("GET", "http://localhost?foo=1a"),
  882. vars: map[string]string{"v1": "1a"},
  883. host: "",
  884. path: "",
  885. query: "foo=1a",
  886. queriesTemplate: "foo={v1:[0-9]{1}(?:a|b)}",
  887. queriesRegexp: "^foo=(?P<v0>[0-9]{1}(?:a|b))$",
  888. shouldMatch: true,
  889. },
  890. {
  891. title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match",
  892. route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
  893. request: newRequest("GET", "http://localhost?foo=12"),
  894. vars: map[string]string{},
  895. host: "",
  896. path: "",
  897. queriesTemplate: "foo={v1:[0-9]{1}}",
  898. queriesRegexp: "^foo=(?P<v0>[0-9]{1})$",
  899. shouldMatch: false,
  900. },
  901. {
  902. title: "Queries route with hyphenated name, match",
  903. route: new(Route).Queries("foo", "{v-1}"),
  904. request: newRequest("GET", "http://localhost?foo=bar"),
  905. vars: map[string]string{"v-1": "bar"},
  906. host: "",
  907. path: "",
  908. query: "foo=bar",
  909. queriesTemplate: "foo={v-1}",
  910. queriesRegexp: "^foo=(?P<v0>.*)$",
  911. shouldMatch: true,
  912. },
  913. {
  914. title: "Queries route with multiple hyphenated names, match",
  915. route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"),
  916. request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
  917. vars: map[string]string{"v-1": "bar", "v-2": "ding"},
  918. host: "",
  919. path: "",
  920. query: "foo=bar&baz=ding",
  921. queriesTemplate: "foo={v-1},baz={v-2}",
  922. queriesRegexp: "^foo=(?P<v0>.*)$,^baz=(?P<v0>.*)$",
  923. shouldMatch: true,
  924. },
  925. {
  926. title: "Queries route with hyphenate name and pattern, match",
  927. route: new(Route).Queries("foo", "{v-1:[0-9]+}"),
  928. request: newRequest("GET", "http://localhost?foo=10"),
  929. vars: map[string]string{"v-1": "10"},
  930. host: "",
  931. path: "",
  932. query: "foo=10",
  933. queriesTemplate: "foo={v-1:[0-9]+}",
  934. queriesRegexp: "^foo=(?P<v0>[0-9]+)$",
  935. shouldMatch: true,
  936. },
  937. {
  938. title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group",
  939. route: new(Route).Queries("foo", "{v-1:[0-9]{1}(?:a|b)}"),
  940. request: newRequest("GET", "http://localhost?foo=1a"),
  941. vars: map[string]string{"v-1": "1a"},
  942. host: "",
  943. path: "",
  944. query: "foo=1a",
  945. queriesTemplate: "foo={v-1:[0-9]{1}(?:a|b)}",
  946. queriesRegexp: "^foo=(?P<v0>[0-9]{1}(?:a|b))$",
  947. shouldMatch: true,
  948. },
  949. {
  950. title: "Queries route with empty value, should match",
  951. route: new(Route).Queries("foo", ""),
  952. request: newRequest("GET", "http://localhost?foo=bar"),
  953. vars: map[string]string{},
  954. host: "",
  955. path: "",
  956. query: "foo=",
  957. queriesTemplate: "foo=",
  958. queriesRegexp: "^foo=.*$",
  959. shouldMatch: true,
  960. },
  961. {
  962. title: "Queries route with empty value and no parameter in request, should not match",
  963. route: new(Route).Queries("foo", ""),
  964. request: newRequest("GET", "http://localhost"),
  965. vars: map[string]string{},
  966. host: "",
  967. path: "",
  968. queriesTemplate: "foo=",
  969. queriesRegexp: "^foo=.*$",
  970. shouldMatch: false,
  971. },
  972. {
  973. title: "Queries route with empty value and empty parameter in request, should match",
  974. route: new(Route).Queries("foo", ""),
  975. request: newRequest("GET", "http://localhost?foo="),
  976. vars: map[string]string{},
  977. host: "",
  978. path: "",
  979. query: "foo=",
  980. queriesTemplate: "foo=",
  981. queriesRegexp: "^foo=.*$",
  982. shouldMatch: true,
  983. },
  984. {
  985. title: "Queries route with overlapping value, should not match",
  986. route: new(Route).Queries("foo", "bar"),
  987. request: newRequest("GET", "http://localhost?foo=barfoo"),
  988. vars: map[string]string{},
  989. host: "",
  990. path: "",
  991. queriesTemplate: "foo=bar",
  992. queriesRegexp: "^foo=bar$",
  993. shouldMatch: false,
  994. },
  995. {
  996. title: "Queries route with no parameter in request, should not match",
  997. route: new(Route).Queries("foo", "{bar}"),
  998. request: newRequest("GET", "http://localhost"),
  999. vars: map[string]string{},
  1000. host: "",
  1001. path: "",
  1002. queriesTemplate: "foo={bar}",
  1003. queriesRegexp: "^foo=(?P<v0>.*)$",
  1004. shouldMatch: false,
  1005. },
  1006. {
  1007. title: "Queries route with empty parameter in request, should match",
  1008. route: new(Route).Queries("foo", "{bar}"),
  1009. request: newRequest("GET", "http://localhost?foo="),
  1010. vars: map[string]string{"foo": ""},
  1011. host: "",
  1012. path: "",
  1013. query: "foo=",
  1014. queriesTemplate: "foo={bar}",
  1015. queriesRegexp: "^foo=(?P<v0>.*)$",
  1016. shouldMatch: true,
  1017. },
  1018. {
  1019. title: "Queries route, bad submatch",
  1020. route: new(Route).Queries("foo", "bar", "baz", "ding"),
  1021. request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"),
  1022. vars: map[string]string{},
  1023. host: "",
  1024. path: "",
  1025. queriesTemplate: "foo=bar,baz=ding",
  1026. queriesRegexp: "^foo=bar$,^baz=ding$",
  1027. shouldMatch: false,
  1028. },
  1029. {
  1030. title: "Queries route with pattern, match, escaped value",
  1031. route: new(Route).Queries("foo", "{v1}"),
  1032. request: newRequest("GET", "http://localhost?foo=%25bar%26%20%2F%3D%3F"),
  1033. vars: map[string]string{"v1": "%bar& /=?"},
  1034. host: "",
  1035. path: "",
  1036. query: "foo=%25bar%26+%2F%3D%3F",
  1037. queriesTemplate: "foo={v1}",
  1038. queriesRegexp: "^foo=(?P<v0>.*)$",
  1039. shouldMatch: true,
  1040. },
  1041. }
  1042. for _, test := range tests {
  1043. t.Run(test.title, func(t *testing.T) {
  1044. testTemplate(t, test)
  1045. testQueriesTemplates(t, test)
  1046. testUseEscapedRoute(t, test)
  1047. testQueriesRegexp(t, test)
  1048. })
  1049. }
  1050. }
  1051. func TestSchemes(t *testing.T) {
  1052. tests := []routeTest{
  1053. // Schemes
  1054. {
  1055. title: "Schemes route, default scheme, match http, build http",
  1056. route: new(Route).Host("localhost"),
  1057. request: newRequest("GET", "http://localhost"),
  1058. scheme: "http",
  1059. host: "localhost",
  1060. shouldMatch: true,
  1061. },
  1062. {
  1063. title: "Schemes route, match https, build https",
  1064. route: new(Route).Schemes("https", "ftp").Host("localhost"),
  1065. request: newRequest("GET", "https://localhost"),
  1066. scheme: "https",
  1067. host: "localhost",
  1068. shouldMatch: true,
  1069. },
  1070. {
  1071. title: "Schemes route, match ftp, build https",
  1072. route: new(Route).Schemes("https", "ftp").Host("localhost"),
  1073. request: newRequest("GET", "ftp://localhost"),
  1074. scheme: "https",
  1075. host: "localhost",
  1076. shouldMatch: true,
  1077. },
  1078. {
  1079. title: "Schemes route, match ftp, build ftp",
  1080. route: new(Route).Schemes("ftp", "https").Host("localhost"),
  1081. request: newRequest("GET", "ftp://localhost"),
  1082. scheme: "ftp",
  1083. host: "localhost",
  1084. shouldMatch: true,
  1085. },
  1086. {
  1087. title: "Schemes route, bad scheme",
  1088. route: new(Route).Schemes("https", "ftp").Host("localhost"),
  1089. request: newRequest("GET", "http://localhost"),
  1090. scheme: "https",
  1091. host: "localhost",
  1092. shouldMatch: false,
  1093. },
  1094. }
  1095. for _, test := range tests {
  1096. t.Run(test.title, func(t *testing.T) {
  1097. testRoute(t, test)
  1098. testTemplate(t, test)
  1099. })
  1100. }
  1101. }
  1102. func TestMatcherFunc(t *testing.T) {
  1103. m := func(r *http.Request, m *RouteMatch) bool {
  1104. return r.URL.Host == "aaa.bbb.ccc"
  1105. }
  1106. tests := []routeTest{
  1107. {
  1108. title: "MatchFunc route, match",
  1109. route: new(Route).MatcherFunc(m),
  1110. request: newRequest("GET", "http://aaa.bbb.ccc"),
  1111. vars: map[string]string{},
  1112. host: "",
  1113. path: "",
  1114. shouldMatch: true,
  1115. },
  1116. {
  1117. title: "MatchFunc route, non-match",
  1118. route: new(Route).MatcherFunc(m),
  1119. request: newRequest("GET", "http://aaa.222.ccc"),
  1120. vars: map[string]string{},
  1121. host: "",
  1122. path: "",
  1123. shouldMatch: false,
  1124. },
  1125. }
  1126. for _, test := range tests {
  1127. t.Run(test.title, func(t *testing.T) {
  1128. testRoute(t, test)
  1129. testTemplate(t, test)
  1130. })
  1131. }
  1132. }
  1133. func TestBuildVarsFunc(t *testing.T) {
  1134. tests := []routeTest{
  1135. {
  1136. title: "BuildVarsFunc set on route",
  1137. route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
  1138. vars["v1"] = "3"
  1139. vars["v2"] = "a"
  1140. return vars
  1141. }),
  1142. request: newRequest("GET", "http://localhost/111/2"),
  1143. path: "/111/3a",
  1144. pathTemplate: `/111/{v1:\d}{v2:.*}`,
  1145. shouldMatch: true,
  1146. },
  1147. {
  1148. title: "BuildVarsFunc set on route and parent route",
  1149. route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
  1150. vars["v1"] = "2"
  1151. return vars
  1152. }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
  1153. vars["v2"] = "b"
  1154. return vars
  1155. }),
  1156. request: newRequest("GET", "http://localhost/1/a"),
  1157. path: "/2/b",
  1158. pathTemplate: `/{v1:\d}/{v2:\w}`,
  1159. shouldMatch: true,
  1160. },
  1161. }
  1162. for _, test := range tests {
  1163. t.Run(test.title, func(t *testing.T) {
  1164. testRoute(t, test)
  1165. testTemplate(t, test)
  1166. })
  1167. }
  1168. }
  1169. func TestSubRouter(t *testing.T) {
  1170. subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter()
  1171. subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter()
  1172. subrouter3 := new(Route).PathPrefix("/foo").Subrouter()
  1173. subrouter4 := new(Route).PathPrefix("/foo/bar").Subrouter()
  1174. subrouter5 := new(Route).PathPrefix("/{category}").Subrouter()
  1175. tests := []routeTest{
  1176. {
  1177. route: subrouter1.Path("/{v2:[a-z]+}"),
  1178. request: newRequest("GET", "http://aaa.google.com/bbb"),
  1179. vars: map[string]string{"v1": "aaa", "v2": "bbb"},
  1180. host: "aaa.google.com",
  1181. path: "/bbb",
  1182. pathTemplate: `/{v2:[a-z]+}`,
  1183. hostTemplate: `{v1:[a-z]+}.google.com`,
  1184. shouldMatch: true,
  1185. },
  1186. {
  1187. route: subrouter1.Path("/{v2:[a-z]+}"),
  1188. request: newRequest("GET", "http://111.google.com/111"),
  1189. vars: map[string]string{"v1": "aaa", "v2": "bbb"},
  1190. host: "aaa.google.com",
  1191. path: "/bbb",
  1192. pathTemplate: `/{v2:[a-z]+}`,
  1193. hostTemplate: `{v1:[a-z]+}.google.com`,
  1194. shouldMatch: false,
  1195. },
  1196. {
  1197. route: subrouter2.Path("/baz/{v2}"),
  1198. request: newRequest("GET", "http://localhost/foo/bar/baz/ding"),
  1199. vars: map[string]string{"v1": "bar", "v2": "ding"},
  1200. host: "",
  1201. path: "/foo/bar/baz/ding",
  1202. pathTemplate: `/foo/{v1}/baz/{v2}`,
  1203. shouldMatch: true,
  1204. },
  1205. {
  1206. route: subrouter2.Path("/baz/{v2}"),
  1207. request: newRequest("GET", "http://localhost/foo/bar"),
  1208. vars: map[string]string{"v1": "bar", "v2": "ding"},
  1209. host: "",
  1210. path: "/foo/bar/baz/ding",
  1211. pathTemplate: `/foo/{v1}/baz/{v2}`,
  1212. shouldMatch: false,
  1213. },
  1214. {
  1215. route: subrouter3.Path("/"),
  1216. request: newRequest("GET", "http://localhost/foo/"),
  1217. vars: map[string]string{},
  1218. host: "",
  1219. path: "/foo/",
  1220. pathTemplate: `/foo/`,
  1221. shouldMatch: true,
  1222. },
  1223. {
  1224. route: subrouter3.Path(""),
  1225. request: newRequest("GET", "http://localhost/foo"),
  1226. vars: map[string]string{},
  1227. host: "",
  1228. path: "/foo",
  1229. pathTemplate: `/foo`,
  1230. shouldMatch: true,
  1231. },
  1232. {
  1233. route: subrouter4.Path("/"),
  1234. request: newRequest("GET", "http://localhost/foo/bar/"),
  1235. vars: map[string]string{},
  1236. host: "",
  1237. path: "/foo/bar/",
  1238. pathTemplate: `/foo/bar/`,
  1239. shouldMatch: true,
  1240. },
  1241. {
  1242. route: subrouter4.Path(""),
  1243. request: newRequest("GET", "http://localhost/foo/bar"),
  1244. vars: map[string]string{},
  1245. host: "",
  1246. path: "/foo/bar",
  1247. pathTemplate: `/foo/bar`,
  1248. shouldMatch: true,
  1249. },
  1250. {
  1251. route: subrouter5.Path("/"),
  1252. request: newRequest("GET", "http://localhost/baz/"),
  1253. vars: map[string]string{"category": "baz"},
  1254. host: "",
  1255. path: "/baz/",
  1256. pathTemplate: `/{category}/`,
  1257. shouldMatch: true,
  1258. },
  1259. {
  1260. route: subrouter5.Path(""),
  1261. request: newRequest("GET", "http://localhost/baz"),
  1262. vars: map[string]string{"category": "baz"},
  1263. host: "",
  1264. path: "/baz",
  1265. pathTemplate: `/{category}`,
  1266. shouldMatch: true,
  1267. },
  1268. {
  1269. title: "Mismatch method specified on parent route",
  1270. route: new(Route).Methods("POST").PathPrefix("/foo").Subrouter().Path("/"),
  1271. request: newRequest("GET", "http://localhost/foo/"),
  1272. vars: map[string]string{},
  1273. host: "",
  1274. path: "/foo/",
  1275. pathTemplate: `/foo/`,
  1276. shouldMatch: false,
  1277. },
  1278. {
  1279. title: "Match method specified on parent route",
  1280. route: new(Route).Methods("POST").PathPrefix("/foo").Subrouter().Path("/"),
  1281. request: newRequest("POST", "http://localhost/foo/"),
  1282. vars: map[string]string{},
  1283. host: "",
  1284. path: "/foo/",
  1285. pathTemplate: `/foo/`,
  1286. shouldMatch: true,
  1287. },
  1288. {
  1289. title: "Mismatch scheme specified on parent route",
  1290. route: new(Route).Schemes("https").Subrouter().PathPrefix("/"),
  1291. request: newRequest("GET", "http://localhost/"),
  1292. vars: map[string]string{},
  1293. host: "",
  1294. path: "/",
  1295. pathTemplate: `/`,
  1296. shouldMatch: false,
  1297. },
  1298. {
  1299. title: "Match scheme specified on parent route",
  1300. route: new(Route).Schemes("http").Subrouter().PathPrefix("/"),
  1301. request: newRequest("GET", "http://localhost/"),
  1302. vars: map[string]string{},
  1303. host: "",
  1304. path: "/",
  1305. pathTemplate: `/`,
  1306. shouldMatch: true,
  1307. },
  1308. {
  1309. title: "No match header specified on parent route",
  1310. route: new(Route).Headers("X-Forwarded-Proto", "https").Subrouter().PathPrefix("/"),
  1311. request: newRequest("GET", "http://localhost/"),
  1312. vars: map[string]string{},
  1313. host: "",
  1314. path: "/",
  1315. pathTemplate: `/`,
  1316. shouldMatch: false,
  1317. },
  1318. {
  1319. title: "Header mismatch value specified on parent route",
  1320. route: new(Route).Headers("X-Forwarded-Proto", "https").Subrouter().PathPrefix("/"),
  1321. request: newRequestWithHeaders("GET", "http://localhost/", "X-Forwarded-Proto", "http"),
  1322. vars: map[string]string{},
  1323. host: "",
  1324. path: "/",
  1325. pathTemplate: `/`,
  1326. shouldMatch: false,
  1327. },
  1328. {
  1329. title: "Header match value specified on parent route",
  1330. route: new(Route).Headers("X-Forwarded-Proto", "https").Subrouter().PathPrefix("/"),
  1331. request: newRequestWithHeaders("GET", "http://localhost/", "X-Forwarded-Proto", "https"),
  1332. vars: map[string]string{},
  1333. host: "",
  1334. path: "/",
  1335. pathTemplate: `/`,
  1336. shouldMatch: true,
  1337. },
  1338. {
  1339. title: "Query specified on parent route not present",
  1340. route: new(Route).Headers("key", "foobar").Subrouter().PathPrefix("/"),
  1341. request: newRequest("GET", "http://localhost/"),
  1342. vars: map[string]string{},
  1343. host: "",
  1344. path: "/",
  1345. pathTemplate: `/`,
  1346. shouldMatch: false,
  1347. },
  1348. {
  1349. title: "Query mismatch value specified on parent route",
  1350. route: new(Route).Queries("key", "foobar").Subrouter().PathPrefix("/"),
  1351. request: newRequest("GET", "http://localhost/?key=notfoobar"),
  1352. vars: map[string]string{},
  1353. host: "",
  1354. path: "/",
  1355. pathTemplate: `/`,
  1356. shouldMatch: false,
  1357. },
  1358. {
  1359. title: "Query match value specified on subroute",
  1360. route: new(Route).Queries("key", "foobar").Subrouter().PathPrefix("/"),
  1361. request: newRequest("GET", "http://localhost/?key=foobar"),
  1362. vars: map[string]string{},
  1363. host: "",
  1364. path: "/",
  1365. pathTemplate: `/`,
  1366. shouldMatch: true,
  1367. },
  1368. {
  1369. title: "Build with scheme on parent router",
  1370. route: new(Route).Schemes("ftp").Host("google.com").Subrouter().Path("/"),
  1371. request: newRequest("GET", "ftp://google.com/"),
  1372. scheme: "ftp",
  1373. host: "google.com",
  1374. path: "/",
  1375. pathTemplate: `/`,
  1376. hostTemplate: `google.com`,
  1377. shouldMatch: true,
  1378. },
  1379. {
  1380. title: "Prefer scheme on child route when building URLs",
  1381. route: new(Route).Schemes("https", "ftp").Host("google.com").Subrouter().Schemes("ftp").Path("/"),
  1382. request: newRequest("GET", "ftp://google.com/"),
  1383. scheme: "ftp",
  1384. host: "google.com",
  1385. path: "/",
  1386. pathTemplate: `/`,
  1387. hostTemplate: `google.com`,
  1388. shouldMatch: true,
  1389. },
  1390. }
  1391. for _, test := range tests {
  1392. t.Run(test.title, func(t *testing.T) {
  1393. testRoute(t, test)
  1394. testTemplate(t, test)
  1395. testUseEscapedRoute(t, test)
  1396. })
  1397. }
  1398. }
  1399. func TestNamedRoutes(t *testing.T) {
  1400. r1 := NewRouter()
  1401. r1.NewRoute().Name("a")
  1402. r1.NewRoute().Name("b")
  1403. r1.NewRoute().Name("c")
  1404. r2 := r1.NewRoute().Subrouter()
  1405. r2.NewRoute().Name("d")
  1406. r2.NewRoute().Name("e")
  1407. r2.NewRoute().Name("f")
  1408. r3 := r2.NewRoute().Subrouter()
  1409. r3.NewRoute().Name("g")
  1410. r3.NewRoute().Name("h")
  1411. r3.NewRoute().Name("i")
  1412. r3.Name("j")
  1413. if r1.namedRoutes == nil || len(r1.namedRoutes) != 10 {
  1414. t.Errorf("Expected 10 named routes, got %v", r1.namedRoutes)
  1415. } else if r1.Get("j") == nil {
  1416. t.Errorf("Subroute name not registered")
  1417. }
  1418. }
  1419. func TestNameMultipleCalls(t *testing.T) {
  1420. r1 := NewRouter()
  1421. rt := r1.NewRoute().Name("foo").Name("bar")
  1422. err := rt.GetError()
  1423. if err == nil {
  1424. t.Errorf("Expected an error")
  1425. }
  1426. }
  1427. func TestStrictSlash(t *testing.T) {
  1428. r := NewRouter()
  1429. r.StrictSlash(true)
  1430. tests := []routeTest{
  1431. {
  1432. title: "Redirect path without slash",
  1433. route: r.NewRoute().Path("/111/"),
  1434. request: newRequest("GET", "http://localhost/111"),
  1435. vars: map[string]string{},
  1436. host: "",
  1437. path: "/111/",
  1438. shouldMatch: true,
  1439. shouldRedirect: true,
  1440. },
  1441. {
  1442. title: "Do not redirect path with slash",
  1443. route: r.NewRoute().Path("/111/"),
  1444. request: newRequest("GET", "http://localhost/111/"),
  1445. vars: map[string]string{},
  1446. host: "",
  1447. path: "/111/",
  1448. shouldMatch: true,
  1449. shouldRedirect: false,
  1450. },
  1451. {
  1452. title: "Redirect path with slash",
  1453. route: r.NewRoute().Path("/111"),
  1454. request: newRequest("GET", "http://localhost/111/"),
  1455. vars: map[string]string{},
  1456. host: "",
  1457. path: "/111",
  1458. shouldMatch: true,
  1459. shouldRedirect: true,
  1460. },
  1461. {
  1462. title: "Do not redirect path without slash",
  1463. route: r.NewRoute().Path("/111"),
  1464. request: newRequest("GET", "http://localhost/111"),
  1465. vars: map[string]string{},
  1466. host: "",
  1467. path: "/111",
  1468. shouldMatch: true,
  1469. shouldRedirect: false,
  1470. },
  1471. {
  1472. title: "Propagate StrictSlash to subrouters",
  1473. route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"),
  1474. request: newRequest("GET", "http://localhost/static/images"),
  1475. vars: map[string]string{},
  1476. host: "",
  1477. path: "/static/images/",
  1478. shouldMatch: true,
  1479. shouldRedirect: true,
  1480. },
  1481. {
  1482. title: "Ignore StrictSlash for path prefix",
  1483. route: r.NewRoute().PathPrefix("/static/"),
  1484. request: newRequest("GET", "http://localhost/static/logo.png"),
  1485. vars: map[string]string{},
  1486. host: "",
  1487. path: "/static/",
  1488. shouldMatch: true,
  1489. shouldRedirect: false,
  1490. },
  1491. }
  1492. for _, test := range tests {
  1493. t.Run(test.title, func(t *testing.T) {
  1494. testRoute(t, test)
  1495. testTemplate(t, test)
  1496. testUseEscapedRoute(t, test)
  1497. })
  1498. }
  1499. }
  1500. func TestUseEncodedPath(t *testing.T) {
  1501. r := NewRouter()
  1502. r.UseEncodedPath()
  1503. tests := []routeTest{
  1504. {
  1505. title: "Router with useEncodedPath, URL with encoded slash does match",
  1506. route: r.NewRoute().Path("/v1/{v1}/v2"),
  1507. request: newRequest("GET", "http://localhost/v1/1%2F2/v2"),
  1508. vars: map[string]string{"v1": "1%2F2"},
  1509. host: "",
  1510. path: "/v1/1%2F2/v2",
  1511. pathTemplate: `/v1/{v1}/v2`,
  1512. shouldMatch: true,
  1513. },
  1514. {
  1515. title: "Router with useEncodedPath, URL with encoded slash doesn't match",
  1516. route: r.NewRoute().Path("/v1/1/2/v2"),
  1517. request: newRequest("GET", "http://localhost/v1/1%2F2/v2"),
  1518. vars: map[string]string{"v1": "1%2F2"},
  1519. host: "",
  1520. path: "/v1/1%2F2/v2",
  1521. pathTemplate: `/v1/1/2/v2`,
  1522. shouldMatch: false,
  1523. },
  1524. }
  1525. for _, test := range tests {
  1526. t.Run(test.title, func(t *testing.T) {
  1527. testRoute(t, test)
  1528. testTemplate(t, test)
  1529. })
  1530. }
  1531. }
  1532. func TestWalkSingleDepth(t *testing.T) {
  1533. r0 := NewRouter()
  1534. r1 := NewRouter()
  1535. r2 := NewRouter()
  1536. r0.Path("/g")
  1537. r0.Path("/o")
  1538. r0.Path("/d").Handler(r1)
  1539. r0.Path("/r").Handler(r2)
  1540. r0.Path("/a")
  1541. r1.Path("/z")
  1542. r1.Path("/i")
  1543. r1.Path("/l")
  1544. r1.Path("/l")
  1545. r2.Path("/i")
  1546. r2.Path("/l")
  1547. r2.Path("/l")
  1548. paths := []string{"g", "o", "r", "i", "l", "l", "a"}
  1549. depths := []int{0, 0, 0, 1, 1, 1, 0}
  1550. i := 0
  1551. err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1552. matcher := route.matchers[0].(*routeRegexp)
  1553. if matcher.template == "/d" {
  1554. return SkipRouter
  1555. }
  1556. if len(ancestors) != depths[i] {
  1557. t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors))
  1558. }
  1559. if matcher.template != "/"+paths[i] {
  1560. t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template)
  1561. }
  1562. i++
  1563. return nil
  1564. })
  1565. if err != nil {
  1566. panic(err)
  1567. }
  1568. if i != len(paths) {
  1569. t.Errorf("Expected %d routes, found %d", len(paths), i)
  1570. }
  1571. }
  1572. func TestWalkNested(t *testing.T) {
  1573. router := NewRouter()
  1574. routeSubrouter := func(r *Route) (*Route, *Router) {
  1575. return r, r.Subrouter()
  1576. }
  1577. gRoute, g := routeSubrouter(router.Path("/g"))
  1578. oRoute, o := routeSubrouter(g.PathPrefix("/o"))
  1579. rRoute, r := routeSubrouter(o.PathPrefix("/r"))
  1580. iRoute, i := routeSubrouter(r.PathPrefix("/i"))
  1581. l1Route, l1 := routeSubrouter(i.PathPrefix("/l"))
  1582. l2Route, l2 := routeSubrouter(l1.PathPrefix("/l"))
  1583. l2.Path("/a")
  1584. testCases := []struct {
  1585. path string
  1586. ancestors []*Route
  1587. }{
  1588. {"/g", []*Route{}},
  1589. {"/g/o", []*Route{gRoute}},
  1590. {"/g/o/r", []*Route{gRoute, oRoute}},
  1591. {"/g/o/r/i", []*Route{gRoute, oRoute, rRoute}},
  1592. {"/g/o/r/i/l", []*Route{gRoute, oRoute, rRoute, iRoute}},
  1593. {"/g/o/r/i/l/l", []*Route{gRoute, oRoute, rRoute, iRoute, l1Route}},
  1594. {"/g/o/r/i/l/l/a", []*Route{gRoute, oRoute, rRoute, iRoute, l1Route, l2Route}},
  1595. }
  1596. idx := 0
  1597. err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1598. path := testCases[idx].path
  1599. tpl := route.regexp.path.template
  1600. if tpl != path {
  1601. t.Errorf(`Expected %s got %s`, path, tpl)
  1602. }
  1603. currWantAncestors := testCases[idx].ancestors
  1604. if !reflect.DeepEqual(currWantAncestors, ancestors) {
  1605. t.Errorf(`Expected %+v got %+v`, currWantAncestors, ancestors)
  1606. }
  1607. idx++
  1608. return nil
  1609. })
  1610. if err != nil {
  1611. panic(err)
  1612. }
  1613. if idx != len(testCases) {
  1614. t.Errorf("Expected %d routes, found %d", len(testCases), idx)
  1615. }
  1616. }
  1617. func TestWalkSubrouters(t *testing.T) {
  1618. router := NewRouter()
  1619. g := router.Path("/g").Subrouter()
  1620. o := g.PathPrefix("/o").Subrouter()
  1621. o.Methods("GET")
  1622. o.Methods("PUT")
  1623. // all 4 routes should be matched
  1624. paths := []string{"/g", "/g/o", "/g/o", "/g/o"}
  1625. idx := 0
  1626. err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1627. path := paths[idx]
  1628. tpl, _ := route.GetPathTemplate()
  1629. if tpl != path {
  1630. t.Errorf(`Expected %s got %s`, path, tpl)
  1631. }
  1632. idx++
  1633. return nil
  1634. })
  1635. if err != nil {
  1636. panic(err)
  1637. }
  1638. if idx != len(paths) {
  1639. t.Errorf("Expected %d routes, found %d", len(paths), idx)
  1640. }
  1641. }
  1642. func TestWalkErrorRoute(t *testing.T) {
  1643. router := NewRouter()
  1644. router.Path("/g")
  1645. expectedError := errors.New("error")
  1646. err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1647. return expectedError
  1648. })
  1649. if err != expectedError {
  1650. t.Errorf("Expected %v routes, found %v", expectedError, err)
  1651. }
  1652. }
  1653. func TestWalkErrorMatcher(t *testing.T) {
  1654. router := NewRouter()
  1655. expectedError := router.Path("/g").Subrouter().Path("").GetError()
  1656. err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1657. return route.GetError()
  1658. })
  1659. if err != expectedError {
  1660. t.Errorf("Expected %v routes, found %v", expectedError, err)
  1661. }
  1662. }
  1663. func TestWalkErrorHandler(t *testing.T) {
  1664. handler := NewRouter()
  1665. expectedError := handler.Path("/path").Subrouter().Path("").GetError()
  1666. router := NewRouter()
  1667. router.Path("/g").Handler(handler)
  1668. err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
  1669. return route.GetError()
  1670. })
  1671. if err != expectedError {
  1672. t.Errorf("Expected %v routes, found %v", expectedError, err)
  1673. }
  1674. }
  1675. func TestSubrouterErrorHandling(t *testing.T) {
  1676. superRouterCalled := false
  1677. subRouterCalled := false
  1678. router := NewRouter()
  1679. router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1680. superRouterCalled = true
  1681. })
  1682. subRouter := router.PathPrefix("/bign8").Subrouter()
  1683. subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1684. subRouterCalled = true
  1685. })
  1686. req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil)
  1687. router.ServeHTTP(NewRecorder(), req)
  1688. if superRouterCalled {
  1689. t.Error("Super router 404 handler called when sub-router 404 handler is available.")
  1690. }
  1691. if !subRouterCalled {
  1692. t.Error("Sub-router 404 handler was not called.")
  1693. }
  1694. }
  1695. // See: https://github.com/gorilla/mux/issues/200
  1696. func TestPanicOnCapturingGroups(t *testing.T) {
  1697. defer func() {
  1698. if recover() == nil {
  1699. t.Errorf("(Test that capturing groups now fail fast) Expected panic, however test completed successfully.\n")
  1700. }
  1701. }()
  1702. NewRouter().NewRoute().Path("/{type:(promo|special)}/{promoId}.json")
  1703. }
  1704. // ----------------------------------------------------------------------------
  1705. // Helpers
  1706. // ----------------------------------------------------------------------------
  1707. func getRouteTemplate(route *Route) string {
  1708. host, err := route.GetHostTemplate()
  1709. if err != nil {
  1710. host = "none"
  1711. }
  1712. path, err := route.GetPathTemplate()
  1713. if err != nil {
  1714. path = "none"
  1715. }
  1716. return fmt.Sprintf("Host: %v, Path: %v", host, path)
  1717. }
  1718. func testRoute(t *testing.T, test routeTest) {
  1719. request := test.request
  1720. route := test.route
  1721. vars := test.vars
  1722. shouldMatch := test.shouldMatch
  1723. query := test.query
  1724. shouldRedirect := test.shouldRedirect
  1725. uri := url.URL{
  1726. Scheme: test.scheme,
  1727. Host: test.host,
  1728. Path: test.path,
  1729. }
  1730. if uri.Scheme == "" {
  1731. uri.Scheme = "http"
  1732. }
  1733. var match RouteMatch
  1734. ok := route.Match(request, &match)
  1735. if ok != shouldMatch {
  1736. msg := "Should match"
  1737. if !shouldMatch {
  1738. msg = "Should not match"
  1739. }
  1740. t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars)
  1741. return
  1742. }
  1743. if shouldMatch {
  1744. if vars != nil && !stringMapEqual(vars, match.Vars) {
  1745. t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars)
  1746. return
  1747. }
  1748. if test.scheme != "" {
  1749. u, err := route.URL(mapToPairs(match.Vars)...)
  1750. if err != nil {
  1751. t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
  1752. }
  1753. if uri.Scheme != u.Scheme {
  1754. t.Errorf("(%v) URLScheme not equal: expected %v, got %v", test.title, uri.Scheme, u.Scheme)
  1755. return
  1756. }
  1757. }
  1758. if test.host != "" {
  1759. u, err := test.route.URLHost(mapToPairs(match.Vars)...)
  1760. if err != nil {
  1761. t.Fatalf("(%v) URLHost error: %v -- %v", test.title, err, getRouteTemplate(route))
  1762. }
  1763. if uri.Scheme != u.Scheme {
  1764. t.Errorf("(%v) URLHost scheme not equal: expected %v, got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route))
  1765. return
  1766. }
  1767. if uri.Host != u.Host {
  1768. t.Errorf("(%v) URLHost host not equal: expected %v, got %v -- %v", test.title, uri.Host, u.Host, getRouteTemplate(route))
  1769. return
  1770. }
  1771. }
  1772. if test.path != "" {
  1773. u, err := route.URLPath(mapToPairs(match.Vars)...)
  1774. if err != nil {
  1775. t.Fatalf("(%v) URLPath error: %v -- %v", test.title, err, getRouteTemplate(route))
  1776. }
  1777. if uri.Path != u.Path {
  1778. t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, uri.Path, u.Path, getRouteTemplate(route))
  1779. return
  1780. }
  1781. }
  1782. if test.host != "" && test.path != "" {
  1783. u, err := route.URL(mapToPairs(match.Vars)...)
  1784. if err != nil {
  1785. t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
  1786. }
  1787. if expected, got := uri.String(), u.String(); expected != got {
  1788. t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, expected, got, getRouteTemplate(route))
  1789. return
  1790. }
  1791. }
  1792. if query != "" {
  1793. u, err := route.URL(mapToPairs(match.Vars)...)
  1794. if err != nil {
  1795. t.Errorf("(%v) erred while creating url: %v", test.title, err)
  1796. return
  1797. }
  1798. if query != u.RawQuery {
  1799. t.Errorf("(%v) URL query not equal: expected %v, got %v", test.title, query, u.RawQuery)
  1800. return
  1801. }
  1802. }
  1803. if shouldRedirect && match.Handler == nil {
  1804. t.Errorf("(%v) Did not redirect", test.title)
  1805. return
  1806. }
  1807. if !shouldRedirect && match.Handler != nil {
  1808. t.Errorf("(%v) Unexpected redirect", test.title)
  1809. return
  1810. }
  1811. }
  1812. }
  1813. func testUseEscapedRoute(t *testing.T, test routeTest) {
  1814. test.route.useEncodedPath = true
  1815. testRoute(t, test)
  1816. }
  1817. func testTemplate(t *testing.T, test routeTest) {
  1818. route := test.route
  1819. pathTemplate := test.pathTemplate
  1820. if len(pathTemplate) == 0 {
  1821. pathTemplate = test.path
  1822. }
  1823. hostTemplate := test.hostTemplate
  1824. if len(hostTemplate) == 0 {
  1825. hostTemplate = test.host
  1826. }
  1827. routePathTemplate, pathErr := route.GetPathTemplate()
  1828. if pathErr == nil && routePathTemplate != pathTemplate {
  1829. t.Errorf("(%v) GetPathTemplate not equal: expected %v, got %v", test.title, pathTemplate, routePathTemplate)
  1830. }
  1831. routeHostTemplate, hostErr := route.GetHostTemplate()
  1832. if hostErr == nil && routeHostTemplate != hostTemplate {
  1833. t.Errorf("(%v) GetHostTemplate not equal: expected %v, got %v", test.title, hostTemplate, routeHostTemplate)
  1834. }
  1835. }
  1836. func testMethods(t *testing.T, test routeTest) {
  1837. route := test.route
  1838. methods, _ := route.GetMethods()
  1839. if strings.Join(methods, ",") != strings.Join(test.methods, ",") {
  1840. t.Errorf("(%v) GetMethods not equal: expected %v, got %v", test.title, test.methods, methods)
  1841. }
  1842. }
  1843. func testRegexp(t *testing.T, test routeTest) {
  1844. route := test.route
  1845. routePathRegexp, regexpErr := route.GetPathRegexp()
  1846. if test.pathRegexp != "" && regexpErr == nil && routePathRegexp != test.pathRegexp {
  1847. t.Errorf("(%v) GetPathRegexp not equal: expected %v, got %v", test.title, test.pathRegexp, routePathRegexp)
  1848. }
  1849. }
  1850. func testQueriesRegexp(t *testing.T, test routeTest) {
  1851. route := test.route
  1852. queries, queriesErr := route.GetQueriesRegexp()
  1853. gotQueries := strings.Join(queries, ",")
  1854. if test.queriesRegexp != "" && queriesErr == nil && gotQueries != test.queriesRegexp {
  1855. t.Errorf("(%v) GetQueriesRegexp not equal: expected %v, got %v", test.title, test.queriesRegexp, gotQueries)
  1856. }
  1857. }
  1858. func testQueriesTemplates(t *testing.T, test routeTest) {
  1859. route := test.route
  1860. queries, queriesErr := route.GetQueriesTemplates()
  1861. gotQueries := strings.Join(queries, ",")
  1862. if test.queriesTemplate != "" && queriesErr == nil && gotQueries != test.queriesTemplate {
  1863. t.Errorf("(%v) GetQueriesTemplates not equal: expected %v, got %v", test.title, test.queriesTemplate, gotQueries)
  1864. }
  1865. }
  1866. type TestA301ResponseWriter struct {
  1867. hh http.Header
  1868. status int
  1869. }
  1870. func (ho *TestA301ResponseWriter) Header() http.Header {
  1871. return http.Header(ho.hh)
  1872. }
  1873. func (ho *TestA301ResponseWriter) Write(b []byte) (int, error) {
  1874. return 0, nil
  1875. }
  1876. func (ho *TestA301ResponseWriter) WriteHeader(code int) {
  1877. ho.status = code
  1878. }
  1879. func Test301Redirect(t *testing.T) {
  1880. m := make(http.Header)
  1881. func1 := func(w http.ResponseWriter, r *http.Request) {}
  1882. func2 := func(w http.ResponseWriter, r *http.Request) {}
  1883. r := NewRouter()
  1884. r.HandleFunc("/api/", func2).Name("func2")
  1885. r.HandleFunc("/", func1).Name("func1")
  1886. req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil)
  1887. res := TestA301ResponseWriter{
  1888. hh: m,
  1889. status: 0,
  1890. }
  1891. r.ServeHTTP(&res, req)
  1892. if "http://localhost/api/?abc=def" != res.hh["Location"][0] {
  1893. t.Errorf("Should have complete URL with query string")
  1894. }
  1895. }
  1896. func TestSkipClean(t *testing.T) {
  1897. func1 := func(w http.ResponseWriter, r *http.Request) {}
  1898. func2 := func(w http.ResponseWriter, r *http.Request) {}
  1899. r := NewRouter()
  1900. r.SkipClean(true)
  1901. r.HandleFunc("/api/", func2).Name("func2")
  1902. r.HandleFunc("/", func1).Name("func1")
  1903. req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil)
  1904. res := NewRecorder()
  1905. r.ServeHTTP(res, req)
  1906. if len(res.HeaderMap["Location"]) != 0 {
  1907. t.Errorf("Shouldn't redirect since skip clean is disabled")
  1908. }
  1909. }
  1910. // https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW
  1911. func TestSubrouterHeader(t *testing.T) {
  1912. expected := "func1 response"
  1913. func1 := func(w http.ResponseWriter, r *http.Request) {
  1914. fmt.Fprint(w, expected)
  1915. }
  1916. func2 := func(http.ResponseWriter, *http.Request) {}
  1917. r := NewRouter()
  1918. s := r.Headers("SomeSpecialHeader", "").Subrouter()
  1919. s.HandleFunc("/", func1).Name("func1")
  1920. r.HandleFunc("/", func2).Name("func2")
  1921. req, _ := http.NewRequest("GET", "http://localhost/", nil)
  1922. req.Header.Add("SomeSpecialHeader", "foo")
  1923. match := new(RouteMatch)
  1924. matched := r.Match(req, match)
  1925. if !matched {
  1926. t.Errorf("Should match request")
  1927. }
  1928. if match.Route.GetName() != "func1" {
  1929. t.Errorf("Expecting func1 handler, got %s", match.Route.GetName())
  1930. }
  1931. resp := NewRecorder()
  1932. match.Handler.ServeHTTP(resp, req)
  1933. if resp.Body.String() != expected {
  1934. t.Errorf("Expecting %q", expected)
  1935. }
  1936. }
  1937. func TestNoMatchMethodErrorHandler(t *testing.T) {
  1938. func1 := func(w http.ResponseWriter, r *http.Request) {}
  1939. r := NewRouter()
  1940. r.HandleFunc("/", func1).Methods("GET", "POST")
  1941. req, _ := http.NewRequest("PUT", "http://localhost/", nil)
  1942. match := new(RouteMatch)
  1943. matched := r.Match(req, match)
  1944. if matched {
  1945. t.Error("Should not have matched route for methods")
  1946. }
  1947. if match.MatchErr != ErrMethodMismatch {
  1948. t.Error("Should get ErrMethodMismatch error")
  1949. }
  1950. resp := NewRecorder()
  1951. r.ServeHTTP(resp, req)
  1952. if resp.Code != 405 {
  1953. t.Errorf("Expecting code %v", 405)
  1954. }
  1955. // Add matching route
  1956. r.HandleFunc("/", func1).Methods("PUT")
  1957. match = new(RouteMatch)
  1958. matched = r.Match(req, match)
  1959. if !matched {
  1960. t.Error("Should have matched route for methods")
  1961. }
  1962. if match.MatchErr != nil {
  1963. t.Error("Should not have any matching error. Found:", match.MatchErr)
  1964. }
  1965. }
  1966. func TestErrMatchNotFound(t *testing.T) {
  1967. emptyHandler := func(w http.ResponseWriter, r *http.Request) {}
  1968. r := NewRouter()
  1969. r.HandleFunc("/", emptyHandler)
  1970. s := r.PathPrefix("/sub/").Subrouter()
  1971. s.HandleFunc("/", emptyHandler)
  1972. // Regular 404 not found
  1973. req, _ := http.NewRequest("GET", "/sub/whatever", nil)
  1974. match := new(RouteMatch)
  1975. matched := r.Match(req, match)
  1976. if matched {
  1977. t.Errorf("Subrouter should not have matched that, got %v", match.Route)
  1978. }
  1979. // Even without a custom handler, MatchErr is set to ErrNotFound
  1980. if match.MatchErr != ErrNotFound {
  1981. t.Errorf("Expected ErrNotFound MatchErr, but was %v", match.MatchErr)
  1982. }
  1983. // Now lets add a 404 handler to subrouter
  1984. s.NotFoundHandler = http.NotFoundHandler()
  1985. req, _ = http.NewRequest("GET", "/sub/whatever", nil)
  1986. // Test the subrouter first
  1987. match = new(RouteMatch)
  1988. matched = s.Match(req, match)
  1989. // Now we should get a match
  1990. if !matched {
  1991. t.Errorf("Subrouter should have matched %s", req.RequestURI)
  1992. }
  1993. // But MatchErr should be set to ErrNotFound anyway
  1994. if match.MatchErr != ErrNotFound {
  1995. t.Errorf("Expected ErrNotFound MatchErr, but was %v", match.MatchErr)
  1996. }
  1997. // Now test the parent (MatchErr should propagate)
  1998. match = new(RouteMatch)
  1999. matched = r.Match(req, match)
  2000. // Now we should get a match
  2001. if !matched {
  2002. t.Errorf("Router should have matched %s via subrouter", req.RequestURI)
  2003. }
  2004. // But MatchErr should be set to ErrNotFound anyway
  2005. if match.MatchErr != ErrNotFound {
  2006. t.Errorf("Expected ErrNotFound MatchErr, but was %v", match.MatchErr)
  2007. }
  2008. }
  2009. // methodsSubrouterTest models the data necessary for testing handler
  2010. // matching for subrouters created after HTTP methods matcher registration.
  2011. type methodsSubrouterTest struct {
  2012. title string
  2013. wantCode int
  2014. router *Router
  2015. // method is the input into the request and expected response
  2016. method string
  2017. // input request path
  2018. path string
  2019. // redirectTo is the expected location path for strict-slash matches
  2020. redirectTo string
  2021. }
  2022. // methodHandler writes the method string in response.
  2023. func methodHandler(method string) http.HandlerFunc {
  2024. return func(w http.ResponseWriter, r *http.Request) {
  2025. w.Write([]byte(method))
  2026. }
  2027. }
  2028. // TestMethodsSubrouterCatchall matches handlers for subrouters where a
  2029. // catchall handler is set for a mis-matching method.
  2030. func TestMethodsSubrouterCatchall(t *testing.T) {
  2031. t.Parallel()
  2032. router := NewRouter()
  2033. router.Methods("PATCH").Subrouter().PathPrefix("/").HandlerFunc(methodHandler("PUT"))
  2034. router.Methods("GET").Subrouter().HandleFunc("/foo", methodHandler("GET"))
  2035. router.Methods("POST").Subrouter().HandleFunc("/foo", methodHandler("POST"))
  2036. router.Methods("DELETE").Subrouter().HandleFunc("/foo", methodHandler("DELETE"))
  2037. tests := []methodsSubrouterTest{
  2038. {
  2039. title: "match GET handler",
  2040. router: router,
  2041. path: "http://localhost/foo",
  2042. method: "GET",
  2043. wantCode: http.StatusOK,
  2044. },
  2045. {
  2046. title: "match POST handler",
  2047. router: router,
  2048. method: "POST",
  2049. path: "http://localhost/foo",
  2050. wantCode: http.StatusOK,
  2051. },
  2052. {
  2053. title: "match DELETE handler",
  2054. router: router,
  2055. method: "DELETE",
  2056. path: "http://localhost/foo",
  2057. wantCode: http.StatusOK,
  2058. },
  2059. {
  2060. title: "disallow PUT method",
  2061. router: router,
  2062. method: "PUT",
  2063. path: "http://localhost/foo",
  2064. wantCode: http.StatusMethodNotAllowed,
  2065. },
  2066. }
  2067. for _, test := range tests {
  2068. t.Run(test.title, func(t *testing.T) {
  2069. testMethodsSubrouter(t, test)
  2070. })
  2071. }
  2072. }
  2073. // TestMethodsSubrouterStrictSlash matches handlers on subrouters with
  2074. // strict-slash matchers.
  2075. func TestMethodsSubrouterStrictSlash(t *testing.T) {
  2076. t.Parallel()
  2077. router := NewRouter()
  2078. sub := router.PathPrefix("/").Subrouter()
  2079. sub.StrictSlash(true).Path("/foo").Methods("GET").Subrouter().HandleFunc("", methodHandler("GET"))
  2080. sub.StrictSlash(true).Path("/foo/").Methods("PUT").Subrouter().HandleFunc("/", methodHandler("PUT"))
  2081. sub.StrictSlash(true).Path("/foo/").Methods("POST").Subrouter().HandleFunc("/", methodHandler("POST"))
  2082. tests := []methodsSubrouterTest{
  2083. {
  2084. title: "match POST handler",
  2085. router: router,
  2086. method: "POST",
  2087. path: "http://localhost/foo/",
  2088. wantCode: http.StatusOK,
  2089. },
  2090. {
  2091. title: "match GET handler",
  2092. router: router,
  2093. method: "GET",
  2094. path: "http://localhost/foo",
  2095. wantCode: http.StatusOK,
  2096. },
  2097. {
  2098. title: "match POST handler, redirect strict-slash",
  2099. router: router,
  2100. method: "POST",
  2101. path: "http://localhost/foo",
  2102. redirectTo: "http://localhost/foo/",
  2103. wantCode: http.StatusMovedPermanently,
  2104. },
  2105. {
  2106. title: "match GET handler, redirect strict-slash",
  2107. router: router,
  2108. method: "GET",
  2109. path: "http://localhost/foo/",
  2110. redirectTo: "http://localhost/foo",
  2111. wantCode: http.StatusMovedPermanently,
  2112. },
  2113. {
  2114. title: "disallow DELETE method",
  2115. router: router,
  2116. method: "DELETE",
  2117. path: "http://localhost/foo",
  2118. wantCode: http.StatusMethodNotAllowed,
  2119. },
  2120. }
  2121. for _, test := range tests {
  2122. t.Run(test.title, func(t *testing.T) {
  2123. testMethodsSubrouter(t, test)
  2124. })
  2125. }
  2126. }
  2127. // TestMethodsSubrouterPathPrefix matches handlers on subrouters created
  2128. // on a router with a path prefix matcher and method matcher.
  2129. func TestMethodsSubrouterPathPrefix(t *testing.T) {
  2130. t.Parallel()
  2131. router := NewRouter()
  2132. router.PathPrefix("/1").Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST"))
  2133. router.PathPrefix("/1").Methods("DELETE").Subrouter().HandleFunc("/2", methodHandler("DELETE"))
  2134. router.PathPrefix("/1").Methods("PUT").Subrouter().HandleFunc("/2", methodHandler("PUT"))
  2135. router.PathPrefix("/1").Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST2"))
  2136. tests := []methodsSubrouterTest{
  2137. {
  2138. title: "match first POST handler",
  2139. router: router,
  2140. method: "POST",
  2141. path: "http://localhost/1/2",
  2142. wantCode: http.StatusOK,
  2143. },
  2144. {
  2145. title: "match DELETE handler",
  2146. router: router,
  2147. method: "DELETE",
  2148. path: "http://localhost/1/2",
  2149. wantCode: http.StatusOK,
  2150. },
  2151. {
  2152. title: "match PUT handler",
  2153. router: router,
  2154. method: "PUT",
  2155. path: "http://localhost/1/2",
  2156. wantCode: http.StatusOK,
  2157. },
  2158. {
  2159. title: "disallow PATCH method",
  2160. router: router,
  2161. method: "PATCH",
  2162. path: "http://localhost/1/2",
  2163. wantCode: http.StatusMethodNotAllowed,
  2164. },
  2165. }
  2166. for _, test := range tests {
  2167. t.Run(test.title, func(t *testing.T) {
  2168. testMethodsSubrouter(t, test)
  2169. })
  2170. }
  2171. }
  2172. // TestMethodsSubrouterSubrouter matches handlers on subrouters produced
  2173. // from method matchers registered on a root subrouter.
  2174. func TestMethodsSubrouterSubrouter(t *testing.T) {
  2175. t.Parallel()
  2176. router := NewRouter()
  2177. sub := router.PathPrefix("/1").Subrouter()
  2178. sub.Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST"))
  2179. sub.Methods("GET").Subrouter().HandleFunc("/2", methodHandler("GET"))
  2180. sub.Methods("PATCH").Subrouter().HandleFunc("/2", methodHandler("PATCH"))
  2181. sub.HandleFunc("/2", methodHandler("PUT")).Subrouter().Methods("PUT")
  2182. sub.HandleFunc("/2", methodHandler("POST2")).Subrouter().Methods("POST")
  2183. tests := []methodsSubrouterTest{
  2184. {
  2185. title: "match first POST handler",
  2186. router: router,
  2187. method: "POST",
  2188. path: "http://localhost/1/2",
  2189. wantCode: http.StatusOK,
  2190. },
  2191. {
  2192. title: "match GET handler",
  2193. router: router,
  2194. method: "GET",
  2195. path: "http://localhost/1/2",
  2196. wantCode: http.StatusOK,
  2197. },
  2198. {
  2199. title: "match PATCH handler",
  2200. router: router,
  2201. method: "PATCH",
  2202. path: "http://localhost/1/2",
  2203. wantCode: http.StatusOK,
  2204. },
  2205. {
  2206. title: "match PUT handler",
  2207. router: router,
  2208. method: "PUT",
  2209. path: "http://localhost/1/2",
  2210. wantCode: http.StatusOK,
  2211. },
  2212. {
  2213. title: "disallow DELETE method",
  2214. router: router,
  2215. method: "DELETE",
  2216. path: "http://localhost/1/2",
  2217. wantCode: http.StatusMethodNotAllowed,
  2218. },
  2219. }
  2220. for _, test := range tests {
  2221. t.Run(test.title, func(t *testing.T) {
  2222. testMethodsSubrouter(t, test)
  2223. })
  2224. }
  2225. }
  2226. // TestMethodsSubrouterPathVariable matches handlers on matching paths
  2227. // with path variables in them.
  2228. func TestMethodsSubrouterPathVariable(t *testing.T) {
  2229. t.Parallel()
  2230. router := NewRouter()
  2231. router.Methods("GET").Subrouter().HandleFunc("/foo", methodHandler("GET"))
  2232. router.Methods("POST").Subrouter().HandleFunc("/{any}", methodHandler("POST"))
  2233. router.Methods("DELETE").Subrouter().HandleFunc("/1/{any}", methodHandler("DELETE"))
  2234. router.Methods("PUT").Subrouter().HandleFunc("/1/{any}", methodHandler("PUT"))
  2235. tests := []methodsSubrouterTest{
  2236. {
  2237. title: "match GET handler",
  2238. router: router,
  2239. method: "GET",
  2240. path: "http://localhost/foo",
  2241. wantCode: http.StatusOK,
  2242. },
  2243. {
  2244. title: "match POST handler",
  2245. router: router,
  2246. method: "POST",
  2247. path: "http://localhost/foo",
  2248. wantCode: http.StatusOK,
  2249. },
  2250. {
  2251. title: "match DELETE handler",
  2252. router: router,
  2253. method: "DELETE",
  2254. path: "http://localhost/1/foo",
  2255. wantCode: http.StatusOK,
  2256. },
  2257. {
  2258. title: "match PUT handler",
  2259. router: router,
  2260. method: "PUT",
  2261. path: "http://localhost/1/foo",
  2262. wantCode: http.StatusOK,
  2263. },
  2264. {
  2265. title: "disallow PATCH method",
  2266. router: router,
  2267. method: "PATCH",
  2268. path: "http://localhost/1/foo",
  2269. wantCode: http.StatusMethodNotAllowed,
  2270. },
  2271. }
  2272. for _, test := range tests {
  2273. t.Run(test.title, func(t *testing.T) {
  2274. testMethodsSubrouter(t, test)
  2275. })
  2276. }
  2277. }
  2278. func ExampleSetURLVars() {
  2279. req, _ := http.NewRequest("GET", "/foo", nil)
  2280. req = SetURLVars(req, map[string]string{"foo": "bar"})
  2281. fmt.Println(Vars(req)["foo"])
  2282. // Output: bar
  2283. }
  2284. // testMethodsSubrouter runs an individual methodsSubrouterTest.
  2285. func testMethodsSubrouter(t *testing.T, test methodsSubrouterTest) {
  2286. // Execute request
  2287. req, _ := http.NewRequest(test.method, test.path, nil)
  2288. resp := NewRecorder()
  2289. test.router.ServeHTTP(resp, req)
  2290. switch test.wantCode {
  2291. case http.StatusMethodNotAllowed:
  2292. if resp.Code != http.StatusMethodNotAllowed {
  2293. t.Errorf(`(%s) Expected "405 Method Not Allowed", but got %d code`, test.title, resp.Code)
  2294. } else if matchedMethod := resp.Body.String(); matchedMethod != "" {
  2295. t.Errorf(`(%s) Expected "405 Method Not Allowed", but %q handler was called`, test.title, matchedMethod)
  2296. }
  2297. case http.StatusMovedPermanently:
  2298. if gotLocation := resp.HeaderMap.Get("Location"); gotLocation != test.redirectTo {
  2299. t.Errorf("(%s) Expected %q route-match to redirect to %q, but got %q", test.title, test.method, test.redirectTo, gotLocation)
  2300. }
  2301. case http.StatusOK:
  2302. if matchedMethod := resp.Body.String(); matchedMethod != test.method {
  2303. t.Errorf("(%s) Expected %q handler to be called, but %q handler was called", test.title, test.method, matchedMethod)
  2304. }
  2305. default:
  2306. expectedCodes := []int{http.StatusMethodNotAllowed, http.StatusMovedPermanently, http.StatusOK}
  2307. t.Errorf("(%s) Expected wantCode to be one of: %v, but got %d", test.title, expectedCodes, test.wantCode)
  2308. }
  2309. }
  2310. func TestSubrouterMatching(t *testing.T) {
  2311. const (
  2312. none, stdOnly, subOnly uint8 = 0, 1 << 0, 1 << 1
  2313. both = subOnly | stdOnly
  2314. )
  2315. type request struct {
  2316. Name string
  2317. Request *http.Request
  2318. Flags uint8
  2319. }
  2320. cases := []struct {
  2321. Name string
  2322. Standard, Subrouter func(*Router)
  2323. Requests []request
  2324. }{
  2325. {
  2326. "pathPrefix",
  2327. func(r *Router) {
  2328. r.PathPrefix("/before").PathPrefix("/after")
  2329. },
  2330. func(r *Router) {
  2331. r.PathPrefix("/before").Subrouter().PathPrefix("/after")
  2332. },
  2333. []request{
  2334. {"no match final path prefix", newRequest("GET", "/after"), none},
  2335. {"no match parent path prefix", newRequest("GET", "/before"), none},
  2336. {"matches append", newRequest("GET", "/before/after"), both},
  2337. {"matches as prefix", newRequest("GET", "/before/after/1234"), both},
  2338. },
  2339. },
  2340. {
  2341. "path",
  2342. func(r *Router) {
  2343. r.Path("/before").Path("/after")
  2344. },
  2345. func(r *Router) {
  2346. r.Path("/before").Subrouter().Path("/after")
  2347. },
  2348. []request{
  2349. {"no match subroute path", newRequest("GET", "/after"), none},
  2350. {"no match parent path", newRequest("GET", "/before"), none},
  2351. {"no match as prefix", newRequest("GET", "/before/after/1234"), none},
  2352. {"no match append", newRequest("GET", "/before/after"), none},
  2353. },
  2354. },
  2355. {
  2356. "host",
  2357. func(r *Router) {
  2358. r.Host("before.com").Host("after.com")
  2359. },
  2360. func(r *Router) {
  2361. r.Host("before.com").Subrouter().Host("after.com")
  2362. },
  2363. []request{
  2364. {"no match before", newRequestHost("GET", "/", "before.com"), none},
  2365. {"no match other", newRequestHost("GET", "/", "other.com"), none},
  2366. {"matches after", newRequestHost("GET", "/", "after.com"), none},
  2367. },
  2368. },
  2369. {
  2370. "queries variant keys",
  2371. func(r *Router) {
  2372. r.Queries("foo", "bar").Queries("cricket", "baseball")
  2373. },
  2374. func(r *Router) {
  2375. r.Queries("foo", "bar").Subrouter().Queries("cricket", "baseball")
  2376. },
  2377. []request{
  2378. {"matches with all", newRequest("GET", "/?foo=bar&cricket=baseball"), both},
  2379. {"matches with more", newRequest("GET", "/?foo=bar&cricket=baseball&something=else"), both},
  2380. {"no match with none", newRequest("GET", "/"), none},
  2381. {"no match with some", newRequest("GET", "/?cricket=baseball"), none},
  2382. },
  2383. },
  2384. {
  2385. "queries overlapping keys",
  2386. func(r *Router) {
  2387. r.Queries("foo", "bar").Queries("foo", "baz")
  2388. },
  2389. func(r *Router) {
  2390. r.Queries("foo", "bar").Subrouter().Queries("foo", "baz")
  2391. },
  2392. []request{
  2393. {"no match old value", newRequest("GET", "/?foo=bar"), none},
  2394. {"no match diff value", newRequest("GET", "/?foo=bak"), none},
  2395. {"no match with none", newRequest("GET", "/"), none},
  2396. {"matches override", newRequest("GET", "/?foo=baz"), none},
  2397. },
  2398. },
  2399. {
  2400. "header variant keys",
  2401. func(r *Router) {
  2402. r.Headers("foo", "bar").Headers("cricket", "baseball")
  2403. },
  2404. func(r *Router) {
  2405. r.Headers("foo", "bar").Subrouter().Headers("cricket", "baseball")
  2406. },
  2407. []request{
  2408. {
  2409. "matches with all",
  2410. newRequestWithHeaders("GET", "/", "foo", "bar", "cricket", "baseball"),
  2411. both,
  2412. },
  2413. {
  2414. "matches with more",
  2415. newRequestWithHeaders("GET", "/", "foo", "bar", "cricket", "baseball", "something", "else"),
  2416. both,
  2417. },
  2418. {"no match with none", newRequest("GET", "/"), none},
  2419. {"no match with some", newRequestWithHeaders("GET", "/", "cricket", "baseball"), none},
  2420. },
  2421. },
  2422. {
  2423. "header overlapping keys",
  2424. func(r *Router) {
  2425. r.Headers("foo", "bar").Headers("foo", "baz")
  2426. },
  2427. func(r *Router) {
  2428. r.Headers("foo", "bar").Subrouter().Headers("foo", "baz")
  2429. },
  2430. []request{
  2431. {"no match old value", newRequestWithHeaders("GET", "/", "foo", "bar"), none},
  2432. {"no match diff value", newRequestWithHeaders("GET", "/", "foo", "bak"), none},
  2433. {"no match with none", newRequest("GET", "/"), none},
  2434. {"matches override", newRequestWithHeaders("GET", "/", "foo", "baz"), none},
  2435. },
  2436. },
  2437. {
  2438. "method",
  2439. func(r *Router) {
  2440. r.Methods("POST").Methods("GET")
  2441. },
  2442. func(r *Router) {
  2443. r.Methods("POST").Subrouter().Methods("GET")
  2444. },
  2445. []request{
  2446. {"matches before", newRequest("POST", "/"), none},
  2447. {"no match other", newRequest("HEAD", "/"), none},
  2448. {"matches override", newRequest("GET", "/"), none},
  2449. },
  2450. },
  2451. {
  2452. "schemes",
  2453. func(r *Router) {
  2454. r.Schemes("http").Schemes("https")
  2455. },
  2456. func(r *Router) {
  2457. r.Schemes("http").Subrouter().Schemes("https")
  2458. },
  2459. []request{
  2460. {"matches overrides", newRequest("GET", "https://www.example.com/"), none},
  2461. {"matches original", newRequest("GET", "http://www.example.com/"), none},
  2462. {"no match other", newRequest("GET", "ftp://www.example.com/"), none},
  2463. },
  2464. },
  2465. }
  2466. // case -> request -> router
  2467. for _, c := range cases {
  2468. t.Run(c.Name, func(t *testing.T) {
  2469. for _, req := range c.Requests {
  2470. t.Run(req.Name, func(t *testing.T) {
  2471. for _, v := range []struct {
  2472. Name string
  2473. Config func(*Router)
  2474. Expected bool
  2475. }{
  2476. {"subrouter", c.Subrouter, (req.Flags & subOnly) != 0},
  2477. {"standard", c.Standard, (req.Flags & stdOnly) != 0},
  2478. } {
  2479. r := NewRouter()
  2480. v.Config(r)
  2481. if r.Match(req.Request, &RouteMatch{}) != v.Expected {
  2482. if v.Expected {
  2483. t.Errorf("expected %v match", v.Name)
  2484. } else {
  2485. t.Errorf("expected %v no match", v.Name)
  2486. }
  2487. }
  2488. }
  2489. })
  2490. }
  2491. })
  2492. }
  2493. }
  2494. // verify that copyRouteConf copies fields as expected.
  2495. func Test_copyRouteConf(t *testing.T) {
  2496. var (
  2497. m MatcherFunc = func(*http.Request, *RouteMatch) bool {
  2498. return true
  2499. }
  2500. b BuildVarsFunc = func(i map[string]string) map[string]string {
  2501. return i
  2502. }
  2503. r, _ = newRouteRegexp("hi", regexpTypeHost, routeRegexpOptions{})
  2504. )
  2505. tests := []struct {
  2506. name string
  2507. args routeConf
  2508. want routeConf
  2509. }{
  2510. {
  2511. "empty",
  2512. routeConf{},
  2513. routeConf{},
  2514. },
  2515. {
  2516. "full",
  2517. routeConf{
  2518. useEncodedPath: true,
  2519. strictSlash: true,
  2520. skipClean: true,
  2521. regexp: routeRegexpGroup{host: r, path: r, queries: []*routeRegexp{r}},
  2522. matchers: []matcher{m},
  2523. buildScheme: "https",
  2524. buildVarsFunc: b,
  2525. },
  2526. routeConf{
  2527. useEncodedPath: true,
  2528. strictSlash: true,
  2529. skipClean: true,
  2530. regexp: routeRegexpGroup{host: r, path: r, queries: []*routeRegexp{r}},
  2531. matchers: []matcher{m},
  2532. buildScheme: "https",
  2533. buildVarsFunc: b,
  2534. },
  2535. },
  2536. }
  2537. for _, tt := range tests {
  2538. t.Run(tt.name, func(t *testing.T) {
  2539. // special case some incomparable fields of routeConf before delegating to reflect.DeepEqual
  2540. got := copyRouteConf(tt.args)
  2541. // funcs not comparable, just compare length of slices
  2542. if len(got.matchers) != len(tt.want.matchers) {
  2543. t.Errorf("matchers different lengths: %v %v", len(got.matchers), len(tt.want.matchers))
  2544. }
  2545. got.matchers, tt.want.matchers = nil, nil
  2546. // deep equal treats nil slice differently to empty slice so check for zero len first
  2547. {
  2548. bothZero := len(got.regexp.queries) == 0 && len(tt.want.regexp.queries) == 0
  2549. if !bothZero && !reflect.DeepEqual(got.regexp.queries, tt.want.regexp.queries) {
  2550. t.Errorf("queries unequal: %v %v", got.regexp.queries, tt.want.regexp.queries)
  2551. }
  2552. got.regexp.queries, tt.want.regexp.queries = nil, nil
  2553. }
  2554. // funcs not comparable, just compare nullity
  2555. if (got.buildVarsFunc == nil) != (tt.want.buildVarsFunc == nil) {
  2556. t.Errorf("build vars funcs unequal: %v %v", got.buildVarsFunc == nil, tt.want.buildVarsFunc == nil)
  2557. }
  2558. got.buildVarsFunc, tt.want.buildVarsFunc = nil, nil
  2559. // finish the deal
  2560. if !reflect.DeepEqual(got, tt.want) {
  2561. t.Errorf("route confs unequal: %v %v", got, tt.want)
  2562. }
  2563. })
  2564. }
  2565. }
  2566. func TestMethodNotAllowed(t *testing.T) {
  2567. handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
  2568. router := NewRouter()
  2569. router.HandleFunc("/thing", handler).Methods(http.MethodGet)
  2570. router.HandleFunc("/something", handler).Methods(http.MethodGet)
  2571. w := NewRecorder()
  2572. req := newRequest(http.MethodPut, "/thing")
  2573. router.ServeHTTP(w, req)
  2574. if w.Code != 405 {
  2575. t.Fatalf("Expected status code 405 (got %d)", w.Code)
  2576. }
  2577. }
  2578. func TestSubrouterNotFound(t *testing.T) {
  2579. handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
  2580. router := NewRouter()
  2581. router.Path("/a").Subrouter().HandleFunc("/thing", handler).Methods(http.MethodGet)
  2582. router.Path("/b").Subrouter().HandleFunc("/something", handler).Methods(http.MethodGet)
  2583. w := NewRecorder()
  2584. req := newRequest(http.MethodPut, "/not-present")
  2585. router.ServeHTTP(w, req)
  2586. if w.Code != 404 {
  2587. t.Fatalf("Expected status code 404 (got %d)", w.Code)
  2588. }
  2589. }
  2590. // mapToPairs converts a string map to a slice of string pairs
  2591. func mapToPairs(m map[string]string) []string {
  2592. var i int
  2593. p := make([]string, len(m)*2)
  2594. for k, v := range m {
  2595. p[i] = k
  2596. p[i+1] = v
  2597. i += 2
  2598. }
  2599. return p
  2600. }
  2601. // stringMapEqual checks the equality of two string maps
  2602. func stringMapEqual(m1, m2 map[string]string) bool {
  2603. nil1 := m1 == nil
  2604. nil2 := m2 == nil
  2605. if nil1 != nil2 || len(m1) != len(m2) {
  2606. return false
  2607. }
  2608. for k, v := range m1 {
  2609. if v != m2[k] {
  2610. return false
  2611. }
  2612. }
  2613. return true
  2614. }
  2615. // stringHandler returns a handler func that writes a message 's' to the
  2616. // http.ResponseWriter.
  2617. func stringHandler(s string) http.HandlerFunc {
  2618. return func(w http.ResponseWriter, r *http.Request) {
  2619. w.Write([]byte(s))
  2620. }
  2621. }
  2622. // newRequest is a helper function to create a new request with a method and url.
  2623. // The request returned is a 'server' request as opposed to a 'client' one through
  2624. // simulated write onto the wire and read off of the wire.
  2625. // The differences between requests are detailed in the net/http package.
  2626. func newRequest(method, url string) *http.Request {
  2627. req, err := http.NewRequest(method, url, nil)
  2628. if err != nil {
  2629. panic(err)
  2630. }
  2631. // extract the escaped original host+path from url
  2632. // http://localhost/path/here?v=1#frag -> //localhost/path/here
  2633. opaque := ""
  2634. if i := len(req.URL.Scheme); i > 0 {
  2635. opaque = url[i+1:]
  2636. }
  2637. if i := strings.LastIndex(opaque, "?"); i > -1 {
  2638. opaque = opaque[:i]
  2639. }
  2640. if i := strings.LastIndex(opaque, "#"); i > -1 {
  2641. opaque = opaque[:i]
  2642. }
  2643. // Escaped host+path workaround as detailed in https://golang.org/pkg/net/url/#URL
  2644. // for < 1.5 client side workaround
  2645. req.URL.Opaque = opaque
  2646. // Simulate writing to wire
  2647. var buff bytes.Buffer
  2648. req.Write(&buff)
  2649. ioreader := bufio.NewReader(&buff)
  2650. // Parse request off of 'wire'
  2651. req, err = http.ReadRequest(ioreader)
  2652. if err != nil {
  2653. panic(err)
  2654. }
  2655. return req
  2656. }
  2657. // create a new request with the provided headers
  2658. func newRequestWithHeaders(method, url string, headers ...string) *http.Request {
  2659. req := newRequest(method, url)
  2660. if len(headers)%2 != 0 {
  2661. panic(fmt.Sprintf("Expected headers length divisible by 2 but got %v", len(headers)))
  2662. }
  2663. for i := 0; i < len(headers); i += 2 {
  2664. req.Header.Set(headers[i], headers[i+1])
  2665. }
  2666. return req
  2667. }
  2668. // newRequestHost a new request with a method, url, and host header
  2669. func newRequestHost(method, url, host string) *http.Request {
  2670. req, err := http.NewRequest(method, url, nil)
  2671. if err != nil {
  2672. panic(err)
  2673. }
  2674. req.Host = host
  2675. return req
  2676. }