dev.mccue/microhttp-session
dev.mccue.microhttp.session
bowbahdoe/microhttp-session
dev.mccue.microhttp.session
provides an interface for encoding session data in microhttp responses and decoding session data from microhttp requests.
Last one from me for this series, I promise. This just took a lot of build up.
If you are making a classical web app, and maybe you should, then you will want to store persistent data about your users.
Most often logins, but other things like flash data are also fair game.
This provides a composable interface to that capability.
This example uses ScopedValues so will require preview features.
import dev.mccue.json.JsonDecoder;
import dev.mccue.microhttp.handler.DelegatingHandler;
import dev.mccue.microhttp.handler.RouteHandler;
import dev.mccue.microhttp.html.HtmlResponse;
import dev.mccue.microhttp.session.ScopedSession;
import dev.mccue.microhttp.session.SessionManager;
import dev.mccue.microhttp.session.SessionStore;
import org.microhttp.EventLoop;
import org.microhttp.Options;
import java.util.List;
import java.util.regex.Pattern;
import static dev.mccue.html.Html.HTML;
void main() throws Exception {
= RouteHandler.of(
var indexHandler "GET",
Pattern.compile("/"),
-> {
request = ScopedSession.get()
var name .get("name", JsonDecoder::string)
.orElse("?");
return new HtmlResponse(HTML."""
<h1> Your name is \{name} </h1>
""");
}
);
= RouteHandler.of(
var nameHandler "GET",
Pattern.compile("/name/(?<name>.+)"),
(matcher, request) -> {
.update(data ->
ScopedSession.with("name", matcher.group("name")));
datareturn new HtmlResponse(HTML."Go back to /");
}
);
= new HtmlResponse(404, HTML."Not Found");
var notFound = new HtmlResponse(500, HTML."Internal Server Error");
var error
// Can also store in encrypted cookies
= SessionStore.inMemory();
var store = SessionManager.builder()
var manager .store(store)
.build();
= ScopedSession.wrap(manager,
var rootHandler new DelegatingHandler(List.of(indexHandler, nameHandler), notFound)
);
= new EventLoop((request, callback) -> {
var eventLoop try {
.accept(rootHandler.handle(request).intoResponse());
callback} catch (Exception e) {
.accept(error.intoResponse());
callback}
});
.start();
eventLoop.join();
eventLoop}