jsr311.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package restful
  2. // Copyright 2013 Ernest Micklei. All rights reserved.
  3. // Use of this source code is governed by a license
  4. // that can be found in the LICENSE file.
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "sort"
  10. "strings"
  11. )
  12. // RouterJSR311 implements the flow for matching Requests to Routes (and consequently Resource Functions)
  13. // as specified by the JSR311 http://jsr311.java.net/nonav/releases/1.1/spec/spec.html.
  14. // RouterJSR311 implements the Router interface.
  15. // Concept of locators is not implemented.
  16. type RouterJSR311 struct{}
  17. // SelectRoute is part of the Router interface and returns the best match
  18. // for the WebService and its Route for the given Request.
  19. func (r RouterJSR311) SelectRoute(
  20. webServices []*WebService,
  21. httpRequest *http.Request) (selectedService *WebService, selectedRoute *Route, err error) {
  22. // Identify the root resource class (WebService)
  23. dispatcher, finalMatch, err := r.detectDispatcher(httpRequest.URL.Path, webServices)
  24. if err != nil {
  25. return nil, nil, NewError(http.StatusNotFound, "")
  26. }
  27. // Obtain the set of candidate methods (Routes)
  28. routes := r.selectRoutes(dispatcher, finalMatch)
  29. if len(routes) == 0 {
  30. return dispatcher, nil, NewError(http.StatusNotFound, "404: Page Not Found")
  31. }
  32. // Identify the method (Route) that will handle the request
  33. route, ok := r.detectRoute(routes, httpRequest)
  34. return dispatcher, route, ok
  35. }
  36. // ExtractParameters is used to obtain the path parameters from the route using the same matching
  37. // engine as the JSR 311 router.
  38. func (r RouterJSR311) ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string {
  39. webServiceExpr := webService.pathExpr
  40. webServiceMatches := webServiceExpr.Matcher.FindStringSubmatch(urlPath)
  41. pathParameters := r.extractParams(webServiceExpr, webServiceMatches)
  42. routeExpr := route.pathExpr
  43. routeMatches := routeExpr.Matcher.FindStringSubmatch(webServiceMatches[len(webServiceMatches)-1])
  44. routeParams := r.extractParams(routeExpr, routeMatches)
  45. for key, value := range routeParams {
  46. pathParameters[key] = value
  47. }
  48. return pathParameters
  49. }
  50. func (RouterJSR311) extractParams(pathExpr *pathExpression, matches []string) map[string]string {
  51. params := map[string]string{}
  52. for i := 1; i < len(matches); i++ {
  53. if len(pathExpr.VarNames) >= i {
  54. params[pathExpr.VarNames[i-1]] = matches[i]
  55. }
  56. }
  57. return params
  58. }
  59. // https://download.oracle.com/otndocs/jcp/jaxrs-1.1-mrel-eval-oth-JSpec/
  60. func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*Route, error) {
  61. candidates := make([]*Route, 0, 8)
  62. for i, each := range routes {
  63. ok := true
  64. for _, fn := range each.If {
  65. if !fn(httpRequest) {
  66. ok = false
  67. break
  68. }
  69. }
  70. if ok {
  71. candidates = append(candidates, &routes[i])
  72. }
  73. }
  74. if len(candidates) == 0 {
  75. if trace {
  76. traceLogger.Printf("no Route found (from %d) that passes conditional checks", len(routes))
  77. }
  78. return nil, NewError(http.StatusNotFound, "404: Not Found")
  79. }
  80. // http method
  81. previous := candidates
  82. candidates = candidates[:0]
  83. for _, each := range previous {
  84. if httpRequest.Method == each.Method {
  85. candidates = append(candidates, each)
  86. }
  87. }
  88. if len(candidates) == 0 {
  89. if trace {
  90. traceLogger.Printf("no Route found (in %d routes) that matches HTTP method %s\n", len(previous), httpRequest.Method)
  91. }
  92. allowed := []string{}
  93. allowedLoop:
  94. for _, candidate := range previous {
  95. for _, method := range allowed {
  96. if method == candidate.Method {
  97. continue allowedLoop
  98. }
  99. }
  100. allowed = append(allowed, candidate.Method)
  101. }
  102. header := http.Header{"Allow": []string{strings.Join(allowed, ", ")}}
  103. return nil, NewErrorWithHeader(http.StatusMethodNotAllowed, "405: Method Not Allowed", header)
  104. }
  105. // content-type
  106. contentType := httpRequest.Header.Get(HEADER_ContentType)
  107. previous = candidates
  108. candidates = candidates[:0]
  109. for _, each := range previous {
  110. if each.matchesContentType(contentType) {
  111. candidates = append(candidates, each)
  112. }
  113. }
  114. if len(candidates) == 0 {
  115. if trace {
  116. traceLogger.Printf("no Route found (from %d) that matches HTTP Content-Type: %s\n", len(previous), contentType)
  117. }
  118. return nil, NewError(http.StatusUnsupportedMediaType, "415: Unsupported Media Type")
  119. }
  120. // accept
  121. previous = candidates
  122. candidates = candidates[:0]
  123. accept := httpRequest.Header.Get(HEADER_Accept)
  124. if len(accept) == 0 {
  125. accept = "*/*"
  126. }
  127. for _, each := range previous {
  128. if each.matchesAccept(accept) {
  129. candidates = append(candidates, each)
  130. }
  131. }
  132. if len(candidates) == 0 {
  133. if trace {
  134. traceLogger.Printf("no Route found (from %d) that matches HTTP Accept: %s\n", len(previous), accept)
  135. }
  136. available := []string{}
  137. for _, candidate := range previous {
  138. available = append(available, candidate.Produces...)
  139. }
  140. return nil, NewError(
  141. http.StatusNotAcceptable,
  142. fmt.Sprintf("406: Not Acceptable\n\nAvailable representations: %s", strings.Join(available, ", ")))
  143. }
  144. // return r.bestMatchByMedia(outputMediaOk, contentType, accept), nil
  145. return candidates[0], nil
  146. }
  147. // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2
  148. // n/m > n/* > */*
  149. func (r RouterJSR311) bestMatchByMedia(routes []Route, contentType string, accept string) *Route {
  150. // TODO
  151. return &routes[0]
  152. }
  153. // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 2)
  154. func (r RouterJSR311) selectRoutes(dispatcher *WebService, pathRemainder string) []Route {
  155. filtered := &sortableRouteCandidates{}
  156. for _, each := range dispatcher.Routes() {
  157. pathExpr := each.pathExpr
  158. matches := pathExpr.Matcher.FindStringSubmatch(pathRemainder)
  159. if matches != nil {
  160. lastMatch := matches[len(matches)-1]
  161. if len(lastMatch) == 0 || lastMatch == "/" { // do not include if value is neither empty nor ‘/’.
  162. filtered.candidates = append(filtered.candidates,
  163. routeCandidate{each, len(matches) - 1, pathExpr.LiteralCount, pathExpr.VarCount})
  164. }
  165. }
  166. }
  167. if len(filtered.candidates) == 0 {
  168. if trace {
  169. traceLogger.Printf("WebService on path %s has no routes that match URL path remainder:%s\n", dispatcher.rootPath, pathRemainder)
  170. }
  171. return []Route{}
  172. }
  173. sort.Sort(sort.Reverse(filtered))
  174. // select other routes from candidates whoes expression matches rmatch
  175. matchingRoutes := []Route{filtered.candidates[0].route}
  176. for c := 1; c < len(filtered.candidates); c++ {
  177. each := filtered.candidates[c]
  178. if each.route.pathExpr.Matcher.MatchString(pathRemainder) {
  179. matchingRoutes = append(matchingRoutes, each.route)
  180. }
  181. }
  182. return matchingRoutes
  183. }
  184. // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 1)
  185. func (r RouterJSR311) detectDispatcher(requestPath string, dispatchers []*WebService) (*WebService, string, error) {
  186. filtered := &sortableDispatcherCandidates{}
  187. for _, each := range dispatchers {
  188. matches := each.pathExpr.Matcher.FindStringSubmatch(requestPath)
  189. if matches != nil {
  190. filtered.candidates = append(filtered.candidates,
  191. dispatcherCandidate{each, matches[len(matches)-1], len(matches), each.pathExpr.LiteralCount, each.pathExpr.VarCount})
  192. }
  193. }
  194. if len(filtered.candidates) == 0 {
  195. if trace {
  196. traceLogger.Printf("no WebService was found to match URL path:%s\n", requestPath)
  197. }
  198. return nil, "", errors.New("not found")
  199. }
  200. sort.Sort(sort.Reverse(filtered))
  201. return filtered.candidates[0].dispatcher, filtered.candidates[0].finalMatch, nil
  202. }
  203. // Types and functions to support the sorting of Routes
  204. type routeCandidate struct {
  205. route Route
  206. matchesCount int // the number of capturing groups
  207. literalCount int // the number of literal characters (means those not resulting from template variable substitution)
  208. nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’)
  209. }
  210. func (r routeCandidate) expressionToMatch() string {
  211. return r.route.pathExpr.Source
  212. }
  213. func (r routeCandidate) String() string {
  214. return fmt.Sprintf("(m=%d,l=%d,n=%d)", r.matchesCount, r.literalCount, r.nonDefaultCount)
  215. }
  216. type sortableRouteCandidates struct {
  217. candidates []routeCandidate
  218. }
  219. func (rcs *sortableRouteCandidates) Len() int {
  220. return len(rcs.candidates)
  221. }
  222. func (rcs *sortableRouteCandidates) Swap(i, j int) {
  223. rcs.candidates[i], rcs.candidates[j] = rcs.candidates[j], rcs.candidates[i]
  224. }
  225. func (rcs *sortableRouteCandidates) Less(i, j int) bool {
  226. ci := rcs.candidates[i]
  227. cj := rcs.candidates[j]
  228. // primary key
  229. if ci.literalCount < cj.literalCount {
  230. return true
  231. }
  232. if ci.literalCount > cj.literalCount {
  233. return false
  234. }
  235. // secundary key
  236. if ci.matchesCount < cj.matchesCount {
  237. return true
  238. }
  239. if ci.matchesCount > cj.matchesCount {
  240. return false
  241. }
  242. // tertiary key
  243. if ci.nonDefaultCount < cj.nonDefaultCount {
  244. return true
  245. }
  246. if ci.nonDefaultCount > cj.nonDefaultCount {
  247. return false
  248. }
  249. // quaternary key ("source" is interpreted as Path)
  250. return ci.route.Path < cj.route.Path
  251. }
  252. // Types and functions to support the sorting of Dispatchers
  253. type dispatcherCandidate struct {
  254. dispatcher *WebService
  255. finalMatch string
  256. matchesCount int // the number of capturing groups
  257. literalCount int // the number of literal characters (means those not resulting from template variable substitution)
  258. nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’)
  259. }
  260. type sortableDispatcherCandidates struct {
  261. candidates []dispatcherCandidate
  262. }
  263. func (dc *sortableDispatcherCandidates) Len() int {
  264. return len(dc.candidates)
  265. }
  266. func (dc *sortableDispatcherCandidates) Swap(i, j int) {
  267. dc.candidates[i], dc.candidates[j] = dc.candidates[j], dc.candidates[i]
  268. }
  269. func (dc *sortableDispatcherCandidates) Less(i, j int) bool {
  270. ci := dc.candidates[i]
  271. cj := dc.candidates[j]
  272. // primary key
  273. if ci.matchesCount < cj.matchesCount {
  274. return true
  275. }
  276. if ci.matchesCount > cj.matchesCount {
  277. return false
  278. }
  279. // secundary key
  280. if ci.literalCount < cj.literalCount {
  281. return true
  282. }
  283. if ci.literalCount > cj.literalCount {
  284. return false
  285. }
  286. // tertiary key
  287. return ci.nonDefaultCount < cj.nonDefaultCount
  288. }