Search code examples
sessionwebsocketcrystal-langkemal

Using Kemal-sessions with websocket


The documentation for the kemal-session module for the Kemal web framework in Crystal provides this example:

require "kemal"
require "kemal-session"

get "/set" do |env|
  env.session.int("number", rand(100)) # set the value of "number"
  "Random number set."
end

get "/get" do |env|
  num  = env.session.int("number") # get the value of "number"
  env.session.int?("hello") # get value or nil, like []?
  "Value of random number is #{num}."
end

Kemal.run

I'm using Kemal with Websocket. I have a code similar to the following example. How can I uses sessions given that I don't have acces to env?

ws "/" do |socket|
  # Send welcome message to the client
  socket.send "Hello from Kemal!"

  # Handle incoming message and echo back to the client
  socket.on_message do |message|
    socket.send "Echo back from server #{message}"
  end

  # Executes when the client is disconnected. You can do the cleaning up here.
  socket.on_close do
    puts "Closing socket"
  end
end

Solution

  • Websocket connections also yields the context. You just need to access it from the block like

    ws "/" do |socket, env|
      env.session.int?("hello")
    end