Created
February 9, 2018 14:35
-
-
Save anonymous/8e9e4fbab749d5f5a504251d481e18bd to your computer and use it in GitHub Desktop.
Shared via Pony Playground
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
use "net/http" | |
use "net" | |
actor Main | |
new create(env: Env) => | |
let http_listen = "localhost" | |
let http_port = "50002" | |
let out = env.out | |
try | |
let auth = env.root as AmbientAuth | |
Launcher(http_listen, http_port, out, NetAuth(auth)) | |
end | |
actor Launcher | |
new create(http_listen: String, http_port: String, out: OutStream, auth: NetAuth) => | |
HTTPServer.create( | |
auth, | |
ListenHandler, | |
BackendMaker, | |
CommonLog(out) | |
where host = http_listen, service = http_port | |
) | |
class ListenHandler | |
fun ref listening(server: HTTPServer ref) => | |
try | |
(let host, let service) = server.local_address().name()? | |
@printf[None]("server listening on %s : %s\n".cstring(), host.string().cstring(), service.string().cstring()) | |
else | |
@printf[None]("server local address unavailable\n".cstring()) | |
server.dispose() | |
end | |
fun ref not_listening(server: HTTPServer ref) => | |
@printf[None]("server not listening\n".cstring()) | |
fun ref closed(server: HTTPServer ref) => | |
@printf[None]("server closed\n".cstring()) | |
class BackendMaker is HandlerFactory | |
fun apply(session: HTTPSession): HTTPHandler^ => | |
BackendHandler.create(session) | |
class BackendHandler is HTTPHandler | |
let _session: HTTPSession | |
new ref create(session: HTTPSession) => | |
_session = session | |
fun ref apply(request: Payload val) => | |
match (request.method, request.url.path) | |
| ("GET", "/status") => _session(Payload.response(StatusOK)) | |
| ("GET", "/state") => _do_the_thing(request) | |
else | |
@printf[None]("404\n".cstring()) | |
_session(Payload.response(StatusNotFound)) | |
end | |
fun ref _do_the_thing(request: Payload val) => | |
let thingy = CbIsh(recover val {(s: String) => | |
@printf[None]("callback called with '%s'\n".cstring(), s.cstring()) | |
@sleep[None](U32(2)) | |
let response = Payload.response() | |
response("X-finished") = "finished" | |
response.add_chunk(s) | |
response.add_chunk("\n") | |
_session(consume response) | |
@printf[None]("callback finished with '%s'\n".cstring(), s.cstring()) | |
} end) | |
thingy.stuff("some output") | |
actor CbIsh | |
let cb: {(String)} val | |
new create(cb': {(String)} val) => | |
cb = cb' | |
be stuff(str: String) => | |
@sleep[None](U32(2)) | |
cb(str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment