创建短链接

793598
2021/11/26 04:38:08

本章将实现创建短链接功能。

模板文件

{%extends "base.html"%} {%block content%}
<main class="p-3">
  <h1>创建你的短网址</h1>
  <form action="/" method="post" autocomplete="off">
    <div class="mb-3">
      <label for="url" class="form-label">网址:</label>
      <input
        type="url"
        class="form-control"
        id="url"
        name="url"
        placeholder="输入你要缩短的网址"
        required
      />
    </div>
    <div class="mb-3">
      <label for="email" class="form-label">邮箱:</label>
      <input
        type="email"
        class="form-control"
        id="email"
        name="email"
        placeholder="输入你的邮箱"
        required
      />
    </div>
    <button type="submit" class="btn btn-primary">提交</button>
  </form>
</main>
{%endblock%}

handler

/// 处理提交的内容
pub async fn index_action(
    Extension(state): Extension<AppState>,
    Form(cu): Form<form::CreateUrl>,
) -> HandlerRedirectResult {
    let id = core::short_url(&cu.url);
    let handler_name = "index_action";
    let client = get_client(&state, handler_name).await?;
    let result = db::create(&client, cu, id)
        .await
        .map_err(log_error(handler_name.to_string()))?;
    let msg = MsgArgs {
        ok: Some(format!("添加成功,短网址是:{}", result.id)),
        err: None,
        target: Some("/".to_string()),
    };
    Ok(redirect_with_msg("/msg", Some(&msg)))
}

/// 首页
pub async fn index() -> HandlerHtmlResult {
    let handler_name = "index";
    let tmpl = IndexTemplate {};
    render(tmpl).map_err(log_error(handler_name.to_string()))
}
  • index_action:用于接收用户提交的表单,并将其作为参数调用数据库操作的函数

  • index:显示表单

数据库操作

pub async fn create(client: &Client, cu: form::CreateUrl, id: String) -> Result<UrlID> {
    // 是否存在
    let result = super::query_one(client, "SELECT id FROM url WHERE id=$1", &[&id]).await;
    match result {
        // 如果已存在,直接返回
        Ok(result) => return Ok(result),
        // 如果不是“未找到”的错误,直接返回
        Err(err) if !err.is_not_found() => return Err(err),
        // 如果不存在,什么也不做,继续下面的代码
        _ => {}
    };
    let result = super::query_one(
        client,
        "INSERT INTO url(id, url, email) VALUES ($1,$2,$3) RETURNING id",
        &[&id, &cu.url, &cu.email],
    )
    .await?;
    Ok(result)
}