| 1 |
% Generated by roxygen2: do not edit by hand |
| 2 |
% Please edit documentation in R/server.R |
| 3 |
\name{handler} |
| 4 |
\alias{handler} |
| 5 |
\title{Create HTTP Handler} |
| 6 |
\usage{ |
| 7 |
handler(path, callback, method = "GET", prefix = FALSE) |
| 8 |
} |
| 9 |
\arguments{ |
| 10 |
\item{path}{URI path to match (e.g., "/api/data", "/users").} |
| 11 |
|
| 12 |
\item{callback}{Function to handle requests. Receives a list with: |
| 13 |
\itemize{ |
| 14 |
\item \code{method} - HTTP method (character) |
| 15 |
\item \code{uri} - Request URI (character) |
| 16 |
\item \code{headers} - Named character vector of headers |
| 17 |
\item \code{body} - Request body (raw vector) |
| 18 |
} |
| 19 |
|
| 20 |
Should return a list with: |
| 21 |
\itemize{ |
| 22 |
\item \code{status} - HTTP status code (integer, default 200) |
| 23 |
\item \code{headers} - Response headers as a named character vector, e.g. |
| 24 |
\code{c("Content-Type" = "application/json")} (optional) |
| 25 |
\item \code{body} - Response body (character or raw) |
| 26 |
}} |
| 27 |
|
| 28 |
\item{method}{[default "GET"] HTTP method to match (e.g., "GET", "POST", |
| 29 |
"PUT", "DELETE"). Use \code{"*"} to match any method.} |
| 30 |
|
| 31 |
\item{prefix}{[default FALSE] Logical, if TRUE matches path as a prefix |
| 32 |
(e.g., "/api" will match "/api/users", "/api/items", etc.).} |
| 33 |
} |
| 34 |
\value{ |
| 35 |
A handler object for use with \code{\link[=http_server]{http_server()}}. |
| 36 |
} |
| 37 |
\description{ |
| 38 |
Creates an HTTP route handler for use with \code{\link[=http_server]{http_server()}}. |
| 39 |
} |
| 40 |
\details{ |
| 41 |
If the callback throws an error, a 500 Internal Server Error |
| 42 |
response is returned to the client. |
| 43 |
} |
| 44 |
\examples{ |
| 45 |
# Simple GET handler |
| 46 |
h1 <- handler("/hello", function(req) { |
| 47 |
list(status = 200L, body = "Hello!") |
| 48 |
}) |
| 49 |
|
| 50 |
# POST handler that echoes the request body |
| 51 |
h2 <- handler("/echo", function(req) { |
| 52 |
list(status = 200L, body = req$body) |
| 53 |
}, method = "POST") |
| 54 |
|
| 55 |
# Catch-all handler for a path prefix |
| 56 |
h3 <- handler("/static", function(req) { |
| 57 |
# Serve static files under /static/* |
| 58 |
}, method = "*", prefix = TRUE) |
| 59 |
|
| 60 |
} |
| 61 |
\seealso{ |
| 62 |
\code{\link[=handler_ws]{handler_ws()}} for WebSocket handlers. Static handlers: |
| 63 |
\code{\link[=handler_file]{handler_file()}}, \code{\link[=handler_directory]{handler_directory()}}, \code{\link[=handler_inline]{handler_inline()}}, |
| 64 |
\code{\link[=handler_redirect]{handler_redirect()}}. |
| 65 |
} |