Here a simple example on how to use sessions with popcorn:
import popcorn
redef class Session
var is_logged = false
end
class AppLogin
super Handler
redef fun get(req, res) do
res.html """
<p>Is logged: {{{req.session.as(not null).is_logged}}}</p>
<form action="/" method="POST">
<input type="submit" value="Login" />
</form>"""
end
redef fun post(req, res) do
req.session.as(not null).is_logged = true
res.redirect("/")
end
end
var app = new App
app.use_before("/*", new SessionInit)
app.use("/", new AppLogin)
app.listen("localhost", 3000)
Notice the use of the SessionInit
on the /*
route. You must use the
SessionInit
first to initialize the request session.
Without that, your request session will be set to null
.
FileServer
action, which is a standard and minimal file server
HttpRequest
class and services to create it
Serializable::inspect
to show more useful information
more_collections :: more_collections
Highly specific, but useful, collections-related classes.serialization :: serialization_core
Abstract services to serialize Nit objects to different formatscore :: union_find
union–find algorithm using an efficient disjoint-set data structure
# Session handlers
#
# Here a simple example on how to use sessions with popcorn:
# ~~~
# import popcorn
#
# redef class Session
# var is_logged = false
# end
#
# class AppLogin
# super Handler
#
# redef fun get(req, res) do
# res.html """
# <p>Is logged: {{{req.session.as(not null).is_logged}}}</p>
# <form action="/" method="POST">
# <input type="submit" value="Login" />
# </form>"""
# end
#
# redef fun post(req, res) do
# req.session.as(not null).is_logged = true
# res.redirect("/")
# end
# end
#
# var app = new App
# app.use_before("/*", new SessionInit)
# app.use("/", new AppLogin)
# app.listen("localhost", 3000)
# ~~~
#
# Notice the use of the `SessionInit` on the `/*` route. You must use the
# `SessionInit` first to initialize the request session.
# Without that, your request session will be set to `null`.
module pop_sessions
import pop_handlers
# Initialize session in request if non existent.
#
# Should be called before any use of the session.
# ~~~
# import popcorn
#
# var app = new App
# app.use_before("/*", new SessionInit)
# # ... other middlewares
# app.listen("localhost", 3000)
# ~~~
class SessionInit
super Handler
redef fun all(req, res) do if req.session == null then req.session = new Session
end
lib/popcorn/pop_sessions.nit:17,1--72,3