require "http/server" module Guff class Handler < ::HTTP::Handler getter :model def initialize(@models : Models) end def call(context : HTTP::Server::Context) # do nothing by default call_next(context) end def with_session(context, &block : Hash(String, String) -> Bool) sid, data = nil, nil if sid = context.request.headers["x-guff-session-id"]? data = Hash(String, String).from_json(@models.session.get(sid) || "{}") else sid = @models.session.add context.request.headers["x-guff-session-id"] = sid data = {} of String => String end save = block.call(data) # save data @models.session.set(sid, data.to_json) if save end private def redirect(context, url : String) context.response.status_code = 302 context.response.headers["location"] = url end end end