-
-
Notifications
You must be signed in to change notification settings - Fork 38
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
39 changed files
with
843 additions
and
495 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license. | ||
import { | ||
listenAndServe, | ||
listenAndServeTLS, | ||
ServeListener, | ||
ServeOptions, | ||
ServerRequest | ||
} from "./server.ts"; | ||
import { createLogger, Logger, Loglevel, namedLogger } from "./logger.ts"; | ||
import ListenOptions = Deno.ListenOptions; | ||
import ListenTLSOptions = Deno.ListenTLSOptions; | ||
import { | ||
createRouter, | ||
Router | ||
} from "./router.ts"; | ||
import { RoutingError } from "./error.ts"; | ||
import { kHttpStatusMessages } from "./serveio.ts"; | ||
|
||
export interface App extends Router { | ||
/** Start listening with given addr */ | ||
listen(addr: string | ListenOptions, opts?: ServeOptions): ServeListener; | ||
|
||
/** Start listening for HTTPS server */ | ||
listenTLS(tlsOptions: ListenTLSOptions, opts?: ServeOptions): ServeListener; | ||
} | ||
|
||
export type AppOptions = { | ||
logger?: Logger; | ||
logLevel?: Loglevel; | ||
}; | ||
|
||
/** Create App */ | ||
export function createApp( | ||
opts: AppOptions = { | ||
logger: createLogger() | ||
} | ||
): App { | ||
const { info, error } = namedLogger("servest:router", opts.logger); | ||
const router = createRouter(); | ||
const finalErrorHandler = async (e: any, req: ServerRequest) => { | ||
if (e instanceof RoutingError) { | ||
await req.respond({ | ||
status: e.status, | ||
body: e.message | ||
}); | ||
} else { | ||
if (e instanceof Error) { | ||
await req.respond({ | ||
status: 500, | ||
body: e.stack | ||
}); | ||
if (e.stack) { | ||
error(e.stack); | ||
} | ||
} else { | ||
await req.respond({ | ||
status: 500, | ||
body: kHttpStatusMessages[500] | ||
}); | ||
error(e); | ||
} | ||
} | ||
}; | ||
const handleRoute = async (p: string, req: ServerRequest) => { | ||
try { | ||
await router.handleRoute(p, req); | ||
} catch (e) { | ||
if (!req.isResponded()) { | ||
await finalErrorHandler(e, req); | ||
} | ||
} finally { | ||
if (!req.isResponded()) { | ||
await finalErrorHandler(new RoutingError(404), req); | ||
} | ||
info(`${req.respondedStatus()} ${req.method} ${req.url}`); | ||
} | ||
}; | ||
function listen( | ||
addr: string | ListenOptions, | ||
opts?: ServeOptions | ||
): ServeListener { | ||
const listener = listenAndServe(addr, req => handleRoute("", req), opts); | ||
info(`listening on ${addr}`); | ||
return listener; | ||
} | ||
function listenTLS( | ||
listenOptions: ListenTLSOptions, | ||
opts?: ServeOptions | ||
): ServeListener { | ||
const listener = listenAndServeTLS( | ||
listenOptions, | ||
req => handleRoute("", req), | ||
opts | ||
); | ||
info(`listening on ${listenOptions.hostname || ""}:${listenOptions.port}`); | ||
return listener; | ||
} | ||
return { ...router, handleRoute, listen, listenTLS }; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license. | ||
import { createApp, App } from "./app.ts"; | ||
import { | ||
assertEquals, | ||
assertMatch | ||
} from "./vendor/https/deno.land/std/testing/asserts.ts"; | ||
import { it, makeGet, assertRoutingError } from "./test_util.ts"; | ||
import { Loglevel, setLevel } from "./logger.ts"; | ||
import { connectWebSocket } from "./vendor/https/deno.land/std/ws/mod.ts"; | ||
setLevel(Loglevel.NONE); | ||
|
||
it("app/ws", t => { | ||
const app = createApp(); | ||
app.handle("/no-response", () => {}); | ||
app.handle("/throw", () => { | ||
throw new Error("throw"); | ||
}); | ||
const get = makeGet(app); | ||
app.ws("/ws", async sock => { | ||
await sock.send("Hello"); | ||
await sock.close(1000); | ||
}); | ||
t.beforeAfterAll(() => { | ||
const l = app.listen({ port: 8899 }); | ||
return () => l.close(); | ||
}); | ||
t.run("should respond if req.respond wasn't called", async () => { | ||
const res = await get("/no-response"); | ||
assertEquals(res.status, 404); | ||
}); | ||
t.run("should respond for unknown path", async () => { | ||
const res = await get("/not-found"); | ||
assertEquals(res.status, 404); | ||
}); | ||
t.run("should handle global error", async () => { | ||
const res = await get("/throw"); | ||
const text = await res.body.text(); | ||
assertEquals(res.status, 500); | ||
assertMatch(text, /Error: throw/); | ||
}); | ||
t.run("should accept ws", async () => { | ||
const sock = await connectWebSocket("ws://127.0.0.1:8899/ws"); | ||
const it = sock.receive(); | ||
const { value: msg1 } = await it.next(); | ||
assertEquals(msg1, "Hello"); | ||
const { value: msg2 } = await it.next(); | ||
assertEquals(msg2, { code: 1000, reason: "" }); | ||
const { done } = await it.next(); | ||
assertEquals(done, true); | ||
assertEquals(sock.isClosed, true); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,8 @@ | ||
import { kHttpStatusMessages } from "./serveio.ts"; | ||
|
||
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license. | ||
export class RoutingError extends Error { | ||
constructor(readonly status: number, readonly msg: string) { | ||
super(msg); | ||
constructor(readonly status: number, msg?: string) { | ||
super(msg ?? kHttpStatusMessages[status]); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license. | ||
import { | ||
findLongestAndNearestMatches, | ||
resolveIndexPath | ||
} from "./matcher.ts"; | ||
import { assertEquals } from "./vendor/https/deno.land/std/testing/asserts.ts"; | ||
import { it } from "./test_util.ts"; | ||
|
||
it("matcher", t => { | ||
type Pat = [string, (string | RegExp)[], number[]][]; | ||
([ | ||
["/foo", ["/foo", "/bar", "/f"], [0]], | ||
["/foo", ["/foo", "/foo/bar"], [0]], | ||
["/foo/bar", ["/", "/foo", "/hoo", "/hoo/foo/bar", "/foo/bar"], [4]], | ||
["/foo/bar/foo", ["/foo", "/foo/bar", "/bar/foo", "/foo/bar/foo"], [3]], | ||
["/foo", ["/", "/hoo", "/hoo/foo"], []], | ||
["/deno/land", [/d(.+?)o/, /d(.+?)d/], [1]], | ||
["/foo", ["/", "/a/foo", "/foo"], [2]], | ||
["/foo", [/\/foo/, /\/bar\/foo/], [0]], | ||
["/foo", [/\/a\/foo/, /\/foo/], [1]] | ||
] as Pat).forEach(([path, pat, idx]) => { | ||
t.run("findLongestAndNearestMatch:" + path, () => { | ||
const matches = findLongestAndNearestMatches(path, pat); | ||
assertEquals(matches.length, idx.length); | ||
for (let i = 0; i < idx.length; i++) { | ||
assertEquals(matches[i][0], idx[i]); | ||
} | ||
}); | ||
}); | ||
|
||
t.run("resolveIndexPath", async () => { | ||
for ( | ||
const [dir, fp, exp] of [ | ||
[".", "/README.md", "README.md"], | ||
["./fixtures/public", "/", "fixtures/public/index.html"], | ||
["./fixtures/public", "/index", "fixtures/public/index.html"], | ||
["./fixtures/public", "/index.html", "fixtures/public/index.html"], | ||
["./fixtures/public", "/nofile", undefined] | ||
] as [string, string, string | undefined][] | ||
) { | ||
assertEquals(await resolveIndexPath(dir, fp), exp); | ||
} | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.