Skip to main content

serve_redirect

Function serve_redirect 

Source
pub fn serve_redirect(
    ctx: &Ctx,
    attachment: &Attachment,
    disposition: Disposition,
    expires_in: u64,
) -> Result<Response>
Expand description

Answers 302 Found to a presigned GET of the attachment (Active Storage’s redirect mode).

For large or popular files: the browser downloads from R2 directly, so the Worker only signs a URL. The redirect may be cached privately for half of expires_in. Authorize before calling it, as with serve: whoever gets the URL can use it until it expires. Settings, costs and errors as presign_get.

§Examples

use axum::{extract::{Path, State}, response::Response};
use ocre::storage::{self, Attachment, Disposition};
use ocre::{Ctx, OptionExt, Result, params};

// GET /videos/{id}/file: a redirect valid one hour.
async fn file(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<Response> {
    let sql = "SELECT file_key AS key, file_filename AS filename, file_content_type AS content_type, \
               file_size AS size FROM videos WHERE id = ?1";
    let video: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
    storage::serve_redirect(&ctx, &video, Disposition::Inline, 3600)
}