Lucky Logo

#Handling Requests

When a request for a path calls an action, the action has access to the request object through a request method.

The request object is an instance of HTTP::Request.

Lucky also provides access to some helpful methods to determine the requested Content-Type.

You can use these methods to direct the request or return different responses.

class Users::Show < BrowserAction
  route do
    if json?
      # The Content-Type is a json request, so let's return some json
      json(Users::ShowSerializer.new(current_user))
    else
      # Just render the page like normal
      render Users::ShowPage
    end
  end
end

#HTTP Headers

#Accessing Headers

If you need to access or set the headers, you can use request.headers or response.headers.

class Dashboard::Index < BrowserAction
  route do
    remote_ip = request.headers["X-Forwarded-For"]?

    if remote_ip
      plain_text "The remote IP is #{remote_ip}"
    else
      plain_text "No remote IP found"
    end
  end
end

#Setting Response Headers

For things like handling CORS, and many other operations like caching, it may be necessary to set response headers. Set these values through the response.headers object.

class Admin::Reports::Show < BrowserAction
  route do
    response.headers["Cache-Control"] = "max-age=150"
    render ShowPage
  end
end

Read more about working with headers in the Crystal docs on HTTP::Headers

#Handling Responses

Finally, every action is required to return one of the available responses:

class Jobs::Reports::Create < ApiAction
  post "/jobs/reports/" do
    # Run some fancy background job
    if plain?
      # plain text request, return some plain text
      plain_text "Job sent for processing"
    else
      # Respond with HEAD 201
      head 201
    end
  end
end

The response object is an instance of HTTP::Server::Response

#Redirecting

You can redirect using the redirect method:

Note that for most methods that link you elsewhere (like redirect, or the link helper in HTML pages) you can pass the action directly if it does not need any params. You can see this in the first redirect example below.

class Users::Create < BrowserAction
  route do
    redirect to: Users::Index # Default status is 302
    redirect to: Users::Show.with(user_id: "user_id") # If the action needs params
    redirect to: "/somewhere_else" # Redirect using a string path
    redirect to: Users::Index, status: 301 # Override status
  end
end

#Redirect statuses

The default status for a redirect is HTTP::Status::FOUND (302), but if you need a different status code, you can pass any HTTP Status Enum