API
This is documentation for all of Compojure's functions and macros, arranged alphabetically within namespace.
Table Of Content
compojure.control
compojure.crypto
compojure.encodings
compojure.html.form-helpers
compojure.html.gen
compojure.html.page-helpers
compojure.http.helpers
compojure.http.multipart
compojure.http.request
compojure.http.response
compojure.http.routes
compojure.http.servlet
compojure.http.session
compojure.map-utils
compojure.ns-utils
compojure.server.common
compojure.server.jetty
compojure.str-utils
compojure.validation
compojure.validation.predicates
compojure.control
(apply-doc name doc? body)
Return a symbol and body with an optional docstring applied.
(decorate func & decorators)
Macro
Wrap a function in one or more decorators.
(decorate-bind decorator funcs & body)
Macro
Wrap named functions in a decorator for a bounded scope.
(decorate-with decorator & funcs)
Macro
Wrap multiple functions in a decorator.
(deftmpl name doc? & body)
Macro
Define a template function. Arguments are passed via key-value pairs. e.g. (deftmpl foo [bar baz] (+ bar baz)) (foo :bar 1 :baz 2)
(domap [item list] & body)
Macro
Similar to doseq, but collects the results into a sequence.
(maybe f x & xs)
Macro
Returns (f x & xs) if x is not nil, otherwise returns nil.
(redef name value)
Macro
Redefine an existing value, keeping the metadata intact.
(return x & body)
Macro
A do block that will always return the argument 'x'.
compojure.crypto
(decrypt key algorithm params s)
Base64 encodes and encrypts a string with the given key and algorithm.
(decrypt-bytes key algorithm params data)
Decrypts a byte array with the given key and algorithm.
(encrypt key algorithm params s)
Base64 encodes and encrypts a string with the given key and algorithm.
(encrypt-bytes key algorithm params data)
Encrypts a byte array with the given key and algorithm.
(gen-iv-param size)
Generates a random IvParameterSpec for use with CBC encryption algorithms.
(gen-key algorithm size)
Generates a SecretKey of the specified algorithm and size.
(gen-uuid )
Generate a random UUID.
(hmac key algorithm data)
Generate a hashed message authentication code with the supplied key and algorithm on some string data.
(secure-random-bytes size)
(secure-random-bytes size algorithm)
Returns a random byte array of the specified size and algorithm. Defaults to SHA1PRNG.
(strict-seq= x y)
Like = for sequences, but always check every value in a sequence.
compojure.encodings
(base64-decode encoded)
Decode a string using base64.
(base64-decode-bytes encoded)
Decode a string using base64 into an array of bytes.
(base64-encode-bytes unencoded)
Encode an array of bytes into a base64 encoded string.
(decode-hex s)
Converts a string of hex into it's corresponding byte array.
(encode-hex array)
Converts a byte array into it's corresponding hex String.
(marshal data)
Serialize a Clojure object in a base64-encoded string.
(unmarshal marshaled)
Unserialize a Clojure object from a base64-encoded string.
(urldecode s)
Decode a urlencoded string using the default encoding.
(urlencode s)
Encode a urlencoded string using the default encoding.
compojure.html.form-helpers
*params*
Parameter map var that form input field functions use to populate their default values.
(check-box name)
(check-box name checked?)
(check-box name checked? value)
Creates a check box.
(decorate-fields decorator & body)
Macro
Wrap all input field functions in a decorator.
(drop-down name options)
(drop-down name options selected)
Creates a drop-down box using the 'select' tag.
(file-upload name)
Creates a file upload input.
(form-to [method action] & body)
Create a form that points to a particular method and route. e.g. (form-to [:put "/post"] ...)
(hidden-field name)
(hidden-field name value)
Creates a hidden input field.
(label name text)
Create a label for an input field with the supplied name.
(password-field name)
Creates a password input field.
(reset-button text)
Create a form reset button.
(select-options options)
(select-options options selected)
Turn a collection into a set of option tags.
(submit-button text)
Create a submit button.
(text-area name)
(text-area name value)
Creates a text area element.
(text-field name)
(text-field name value)
Creates a text input field.
(with-params params & body)
Macro
Bind a map of params to *params*.
compojure.html.gen
(escape-html string)
Change special characters into HTML character entities.
(explicit-ending-tag? tag)
Returns true if tag needs an explicit ending tag, even if the body of the tag is empty.
h
Shortcut for escape-html
(html & trees)
Format trees of vectors into a string of HTML.
(html-tree tree)
Turns a tree of vectors into a string of HTML. Any sequences in the tree are expanded out.
(optional-attrs func)
Adds an optional attribute map to the supplied function's arguments.
compojure.html.page-helpers
(include-css & styles)
Include a list of external stylesheet files.
(include-js & scripts)
Include a list of external javascript files.
(javascript-tag script)
Wrap the supplied javascript up in script tags and a CDATA section.
(link-to url & content)
Wraps some content in a HTML hyperlink with the supplied URL.
(ordered-list coll)
Wrap a collection in an unordered list
(unordered-list coll)
Wrap a collection in an unordered list
(url-encode string-or-map)
Encodes a single string or sequence of key/value pairs.
(url-params address param-map)
Encodes a map of parameters and adds them onto the end of an existing address. e.g. (url-params "http://example.com" {:lang "en", :offset 10}) => "http://example.com?lang=en&offset=10"
(xhtml-tag lang & contents)
Create an XHTML tag for the specified locale. e.g. (xhtml "en" [:head ...] [:body ...])
compojure.http.helpers
(content-type type)
Retuns a Content-Type header given a type string.
(header-option [k v])
Converts a header option KeyValue into a string.
(header-options m delim)
Converts a map into an HTTP header options string.
(page-not-found )
(page-not-found filename)
A shortcut to create a '404 Not Found' HTTP response.
(redirect-to location)
A shortcut for a '302 Moved' HTTP redirect.
(serve-file path)
(serve-file root path)
Attempts to serve up a static file from a directory, which defaults to './public'. Nil is returned if the file does not exist. If the file is a directory, the function looks for a file in the directory called 'index.*'.
(set-cookie name value)
(set-cookie name value & attrs)
Return a Set-Cookie header.
(with-cache-control handler m)
Middleware to set the Cache-Control http header. Map entries with boolean values either write their key's (name) if true, or nothing if false. Example: (... {:max-age 3600 :public false :must-revalidate true}) Cache-Control: max-age=3600, must-revalidate
(with-headers handler headers)
Merges a map of header name and values into the response. Will not overwrite existing headers.
compojure.http.multipart
(get-multipart-params request)
Retrieve multipart params from the request.
(multipart-form? request)
Does a request have a multipart form?
(parse-multipart-params request)
Parse a map of multipart parameters from the request.
(with-multipart handler)
Decorate a Ring handler with multipart parameters.
compojure.http.request
(assoc-cookies request)
Associate cookies with a request map.
(assoc-params request)
Associate urlencoded parameters with a request. The following keys are added to the request map: :query-params, :form-params and :params.
(get-character-encoding request)
Get the character encoding, or use the default from duck-streams.
(parse-cookies request)
Pull out a map of cookies from a request map.
(parse-form-params request)
Parse urlencoded form parameters from the request body.
(parse-query-params request)
Parse parameters from the query string.
(urlencoded-form? request)
Does a request have a urlencoded form?
(with-cookies handler)
Decorator that adds cookies to a request map.
(with-request-params handler)
Decorator that adds urlencoded parameters to the request map.
compojure.http.response
(create-response request x)
Create a new response map from an update object, x.
default-response
Default HTTP response map.
update-response
Update a response with an object. The type of object determines how the response is updated.
compojure.http.routes
(ANY path & body)
Macro
Generate a route that matches any method.
(DELETE path & body)
Macro
Generate a DELETE route.
(GET path & body)
Macro
Generate a GET route.
(HEAD path & body)
Macro
Generate a HEAD route.
(POST path & body)
Macro
Generate a POST route.
(PUT path & body)
Macro
Generate a PUT route.
(absolute-url? s)
True if the string is an absolute URL.
(assoc-route-params request params)
Associate route parameters with the request map.
compile-matcher
Compile a string or regex into a form suitable for buing passed to the match-uri function.
(compile-route method path body)
Compile a route in the form (method path & body) into a function.
(compile-uri-matcher path)
Compile a path string using the routes syntax into a uri-matcher struct.
(defroutes name doc? & routes)
Macro
Define a Ring handler function from a sequence of routes. Takes an optional doc-string.
(get-matcher-uri path request)
Get the appropriate request URI for the given path pattern.
(match-method method request)
True if this request matches the supplied method.
match-uri
Match a URL against a compiled URI-matcher or a regular expression. Returns the matched URI keywords as a map, or the matched regex groups as a vector.
(request-matcher method path)
Macro
Compiles a function to match a HTTP request against the supplied method and path template. Returns a map of the route parameters if the is a match, nil otherwise. Precompiles the route when supplied with a literal string.
(request-url request)
Return the complete URL for the request.
(routes & handlers)
Create a Ring handler by combining several routes into one. Adds parameters and cookies to the request.
(routes* & handlers)
Create a Ring handler by combining several handlers into one.
(with-request-bindings request & body)
Macro
Add shortcut bindings for the keys in a request map.
compojure.http.servlet
(create-request request servlet)
Create the request map from the HttpServletRequest object.
(defservice routes)
(defservice prefix routes)
Macro
Defines a service method with an optional prefix suitable for being used by genclass to compile a HttpServlet class. e.g. (defservice my-routes) (defservice "my-prefix-" my-routes)
(request-handler [servlet request response] routes)
Handle incoming HTTP requests from a servlet.
(servlet routes)
Create a servlet from a sequence of routes. Automatically updates if the routes binding is redefined.
(update-servlet-response response {:keys [status headers body]})
Update the HttpServletResponse using a response map.
compojure.http.session
(alter-session func & args)
Use a function to alter the session.
(assoc-expiry repository session)
Associate an :expires-at key with the session if the session repository contains the :expires key.
(assoc-flash request)
Associate the session flash with the request and remove it from the session.
(assoc-session request repository)
Associate the session with the request.
create-session
Create a new session map. Should not attempt to save the session.
destroy-session
Remove the session from the session store.
(flash-assoc & keyvals)
Associate key value pairs with the session flash.
read-session
Read in the session using the supplied data. Usually the data is a key used to find the session in a store.
(save-handler-session repository request response session)
Save the session for a handler if required.
(session-assoc & keyvals)
Associate key value pairs with the session.
session-cookie
Return the session data to be stored in the cookie. This is usually the session ID.
(session-crypt repository func session)
Encrypt or decrypt session data.
(session-dissoc & keys)
Dissociate keys from the session.
(session-expired? session)
True if this session's timestamp is in the past.
(session-hmac repository cookie-data)
Calculate a HMAC for a marshalled session. Uses the :hash-key and :hash-algorithm of the :encryption repository map.
(set-session session)
Return a response map with the session set.
(set-session-cookie repository request response session)
Set the session cookie on the response if required.
(timestamp-after seconds)
Return the current time plus seconds as milliseconds.
(with-session handler)
(with-session handler repository)
Wrap a handler in a session of the specified type. Session type defaults to :memory if not supplied.
write-session
Write a new or existing session to the session store.
compojure.map-utils
(assoc-vec map key val)
Associate a key with a value. If the key already exists in the map, create a vector of values.
compojure.ns-utils
(immigrate & ns-names)
Create a public var in this namespace for each public var in the namespaces named by ns-names. The created vars have the same name, value, and metadata as the original except that their :ns metadata value is this namespace.
compojure.server.common
(get-host-and-path url-or-path)
Splits a path or URL into its hostname and path.
(server-with-options creator options servlets)
Create a new server using the supplied function, options and servlets.
compojure.server.jetty
(add-servlet! server url-or-path servlet)
Add a servlet to a Jetty server. Servlets can be connected to a relative path or an absolute URL. When connected to a URL, the function will try and use the hostname to set up a virtual host. Wildcards for the domain and path are allowed.
(defserver name & args)
Macro
Shortcut for (def name (http-server args))
(get-context server)
(get-context server host)
Get a Context instance for a server and hostname.
(jetty-server options? & servlets)
Create a new Jetty HTTP server with the supplied options and servlets.
(run-server & server-args)
Create and start a new Jetty HTTP server.
(servlet-holder servlet & params)
Wrap a servlet in a ServletHolder object with a supplied set of parameters to be set on servlet init.
(start server)
Start a HTTP server.
(stop server)
Stop a HTTP server.
compojure.str-utils
(blank? s)
True if s = "" or nil
(capitalize s)
Uppercase the first letter of a string, and lowercase the rest.
(escape chars string)
Returns a string with each occurance of a character in chars escaped.
(grep re coll)
Filter a collection of strings by a regex.
(indent text)
(indent text spacer)
Indent each line in a string of text. Defaults to an indentation of two spaces.
(lines coll)
Concatenate a sequence of strings into lines of a single string.
(map-str func coll)
Map a function to a collection, then concatenate the results into a string.
(re-escape string)
Escape all special regex chars in string.
(str* & args)
A version of str that prefers the names of Named objects. e.g (str "Hello " :World) => "Hello :World" (str* "Hello " :World) => "Hello World"
(upcase-name sym)
Upcase a symbol or keyword's name.
compojure.validation
*errors*
Var containing validation errors.
(error-class func)
Decorator function that marks an input field with an error class if the parameter has errors.
(error-summary )
Returns a summary of the errors on the form in HTML.
(merge-errors & results)
Merge a set of validation errors into a single hash map.
(validate params pred message)
(validate params name pred message)
Validate a single parameter, or group of parameters, using a predicate. If the predicate fails, a validation error is returned. For a single parameter, use the following form: (validate params name pred message) This will use the value of (pred (params name)) to determine if the parameter is valid. For multiple parameters: (validate params pred message) This will use the value of (pred params) to determine validity.
(validation params & validations)
Convinience function to perform a series of validations on a map of params. Takes a set of params and a collection of argument vectors for the validate function: e.g. (validation params [name pred message] [pred message]) Is the same as: (merge-errors (validate params name pred message) (validate params pred message))
(validation-errors? )
True if there are errors in the var *errors*.
(with-validated-params params validation-fn & body)
Macro
Equivalent to (with-params params (with-validation validation-fn)).
(with-validation validation-fn & body)
Macro
Binds *errors* to (validation-fn *params*).
compojure.validation.predicates
(max-size n)
Returns a function to check a maximum size of a collection.
(present? x)
True if x is not nil and not an empty string.