espresso/response
Module for interacting and sending HTTP responses.
Forked from: https://github.com/gleam-lang/http/blob/v3.2.0/src/gleam/http/response.gleam
Types
Functions
pub fn expire_cookie(response: Response(a), name: String, attributes: Attributes) -> Response(
a,
)
Expire a cookie value for a client
Note: The attributes value should be the same as when the response cookie was set.
pub fn get_cookies(resp: Response(a)) -> List(#(String, String))
Fetch the cookies sent in a response.
Badly formed cookies will be discarded.
pub fn get_header(response: Response(a), key: String) -> Result(
String,
Nil,
)
Get the value for a given header.
If the response does not have that header then Error(Nil)
is returned.
pub fn json(data: Json) -> Response(BitBuilder)
Given json data, sends a 200 response with the json data as the body.
Example
import espresso/request.{Request}
import espresso/response
import cat
fn handler(_req: Request) {
Cat(name: "Test")
|> cat.encode()
|> response.json()
}
pub fn json2(res: Response(a), data: Json) -> Response(BitBuilder)
Similar to json
but allows you to override more fields in the response.
Example
import espresso/request.{Request}
import espresso/response
import cat
fn handler(_req: Request) {
let cat = Cat(name: "Test")
201
|> response.new()
|> response.json2(cat.encode(cat))
}
pub fn map(response: Response(a), transform: fn(a) -> b) -> Response(
b,
)
Update the body of a response using a given function.
pub fn new(status: Int) -> Response(String)
Construct an empty Response.
The body type of the returned response is String
and could be set with a
call to set_body
.
pub fn prepend_header(response: Response(a), key: String, value: String) -> Response(
a,
)
Prepend the header with the given value under the given header key.
Similar to set_header
except if the header already exists it prepends
another header with the same key.
pub fn redirect(uri: String) -> Response(String)
Create a response that redirects to the given uri.
pub fn send(status: Int, body: String) -> Response(BitBuilder)
sends a generic response with the given status code and text body.
Example
import espresso/request.{Request}
fn handler(_req: Request) {
response.send(200, "Hello World")
}
pub fn set_body(response: Response(a), body: b) -> Response(b)
Set the body of the response, overwriting any existing body.
pub fn set_cookie(response: Response(a), name: String, value: String, attributes: Attributes) -> Response(
a,
)
Set a cookie value for a client
pub fn set_header(response: Response(a), key: String, value: String) -> Response(
a,
)
Set the header with the given value under the given header key.
If the response already has that key, it is replaced.