|
| 1 | +use web |
| 2 | +import web/Application |
| 3 | +import structs/LinkedList |
| 4 | +import text/regexp/Regexp |
| 5 | + |
| 6 | +/** |
| 7 | + * Routes a request to a specific application by |
| 8 | + * matching the requested path to a matched pattern. |
| 9 | + */ |
| 10 | +Router: class extends Application { |
| 11 | + _routes: LinkedList<Regexp> |
| 12 | + _currentApp: Application |
| 13 | + _notFoundApp: Application |
| 14 | + |
| 15 | + init: func ~withNotFound (=_notFoundApp) { |
| 16 | + _routes = LinkedList<Regexp> new() |
| 17 | + } |
| 18 | + |
| 19 | + init: func ~useDefaultNotFound { |
| 20 | + this(DefaultNotFoundApplication new()) |
| 21 | + } |
| 22 | + |
| 23 | + addRoute: func(pattern: String, app: Application) { |
| 24 | + _routes add(Route new(pattern, app)) |
| 25 | + } |
| 26 | + |
| 27 | + removeRoute: func(pattern: String) { |
| 28 | + //TODO: implement me |
| 29 | + } |
| 30 | + |
| 31 | + parseRequest: func { |
| 32 | + // Attempt to patch requested path to a route |
| 33 | + for (route: Route in _routes) { |
| 34 | + if (route matches(request path)) { |
| 35 | + _currentApp = route application |
| 36 | + break |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // If no match found, use not found app |
| 41 | + if (!_currentApp) _currentApp = _notFoundApp |
| 42 | + |
| 43 | + _currentApp request = request |
| 44 | + _currentApp parseRequest() |
| 45 | + } |
| 46 | + |
| 47 | + sendHeaders: func(headers: HeaderMap) { |
| 48 | + _currentApp sendHeaders(headers) |
| 49 | + } |
| 50 | + |
| 51 | + sendResponse: func(response: ResponseWriter) { |
| 52 | + _currentApp sendResponse(response) |
| 53 | + _currentApp = null |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +Route: class { |
| 58 | + application: Application |
| 59 | + patternRegexp: Regexp |
| 60 | + |
| 61 | + init: func(pattern: String, =application) { |
| 62 | + patternRegexp = Regexp new(pattern) |
| 63 | + } |
| 64 | + |
| 65 | + matches: func(path: String) -> Bool { |
| 66 | + return patternRegexp matches(path) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +DefaultNotFoundApplication: class extends Application { |
| 71 | + sendHeaders: func(headers: HeaderMap) { |
| 72 | + headers["Content-type"] = "text/html" |
| 73 | + } |
| 74 | + |
| 75 | + sendResponse: func(response: ResponseWriter) { |
| 76 | + response write("<html><body><h1>Page not found!</h1></body></html>") |
| 77 | + } |
| 78 | +} |
| 79 | + |
0 commit comments