aboutsummaryrefslogtreecommitdiff
path: root/src/guff/handler.cr
blob: b44e836589038ef7f24bea122fd40ee53055d8db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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