#Handling Requests

When a request comes in to an Action, Lucky gives you access to the request object through the request method.

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

Lucky gives you access to a few helpful methods based on the request Content-Type.

You can use these methods to help 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

#Accessing Headers

If you need to access the request headers, you can use the headers method.

class Dashboard::Index < BrowserAction
  route do
    remote_ip = headers["X-Forwarded-For"]?
    if remote_ip
      text "The remote IP is #{remote_ip}"
    else
      text "No remote IP found"
    end
  end
end

#Handling Responses

Once you’ve recieved your request, and handled it, you’ll need to return a response. Every Lucky::Action requires that a response is returned.

class Jobs::Reports::Create < ApiAction
  post "/jobs/reports/" do
    # Run some fancy background job
    if plain?
      # plain text request, return some plain text
      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

#Setting Response Headers

For things like handling CORS, and many other operations like cacheing, it may be necessary to set special 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

#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