Modelo do encurtador em FastAPI

Gerado a partir de deploy-templates/fastapi (dado.cloud 4c2a882).
This commit is contained in:
dado.cloud
2026-10-21 12:27:03 +00:00
commit 239d0dee0a
8 changed files with 633 additions and 0 deletions
+278
View File
@@ -0,0 +1,278 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Encurtador de links</title>
<meta name="description" content="Encurte links e acompanhe quantas vezes cada um foi aberto." />
<link
rel="icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%233b5bdb'/%3E%3Cpath d='M13.5 18.5l5-5M12 15l-2 2a3.5 3.5 0 005 5l2-2M20 17l2-2a3.5 3.5 0 00-5-5l-2 2' stroke='white' stroke-width='2.2' fill='none' stroke-linecap='round'/%3E%3C/svg%3E"
/>
<style>
/* Mesmo visual nos modelos Next.js, Express e FastAPI. Mude à vontade. */
:root {
--fundo: #f6f7f9;
--cartao: #ffffff;
--texto: #14161a;
--suave: #5b6270;
--borda: #e3e6eb;
--destaque: #3b5bdb;
--destaque-texto: #ffffff;
--destaque-suave: #edf1ff;
--erro: #c92a2a;
--raio: 14px;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--fundo: #0f1115;
--cartao: #171a21;
--texto: #eceef2;
--suave: #9aa1ad;
--borda: #2a2f3a;
--destaque: #8299ff;
--destaque-texto: #0f1115;
--destaque-suave: #1e2540;
--erro: #ff8787;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: var(--fundo);
color: var(--texto);
line-height: 1.5;
-webkit-text-size-adjust: 100%;
}
.pagina { max-width: 640px; margin: 0 auto; padding: 56px 16px 32px; }
.topo { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
.marca {
flex: none; width: 40px; height: 40px; border-radius: 10px;
background: var(--destaque); color: var(--destaque-texto);
display: grid; place-items: center;
}
h1 { font-size: 28px; line-height: 1.2; margin: 0; letter-spacing: -0.02em; }
h2 { font-size: 16px; margin: 32px 0 12px; }
.lead { color: var(--suave); margin: 0 0 24px; }
.cartao { background: var(--cartao); border: 1px solid var(--borda); border-radius: var(--raio); padding: 20px; }
.formulario { display: flex; gap: 8px; }
.formulario input {
flex: 1; min-width: 0; font: inherit; padding: 12px 14px;
border: 1px solid var(--borda); border-radius: 10px;
background: var(--fundo); color: var(--texto);
}
.formulario input:focus { outline: 2px solid var(--destaque); outline-offset: 1px; }
button {
font: inherit; font-weight: 600; padding: 12px 20px; border: 0; border-radius: 10px;
background: var(--destaque); color: var(--destaque-texto); cursor: pointer; white-space: nowrap;
}
button:disabled { opacity: 0.6; cursor: progress; }
button:focus-visible, a:focus-visible { outline: 2px solid var(--destaque); outline-offset: 2px; }
.secundario { background: var(--cartao); color: var(--destaque); border: 1px solid var(--borda); padding: 8px 14px; }
.erro { color: var(--erro); margin: 10px 0 0; font-size: 14px; }
.resultado {
margin-top: 16px; display: flex; align-items: center; gap: 12px;
padding: 12px 14px; border-radius: 10px; background: var(--destaque-suave);
}
.resultado a {
flex: 1; min-width: 0; font-family: var(--mono); font-weight: 600;
color: var(--destaque); text-decoration: none; overflow-wrap: anywhere;
}
.lista { list-style: none; margin: 0; padding: 0; }
.lista li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-top: 1px solid var(--borda); }
.lista li:first-child { border-top: 0; padding-top: 0; }
.lista li:last-child { padding-bottom: 0; }
.link-info { flex: 1; min-width: 0; }
.link-info a { font-family: var(--mono); font-weight: 600; color: var(--texto); text-decoration: none; overflow-wrap: anywhere; }
.link-info a:hover { color: var(--destaque); }
.destino { display: block; color: var(--suave); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cliques { font-family: var(--mono); font-size: 14px; color: var(--suave); white-space: nowrap; }
.vazio { color: var(--suave); margin: 0; }
.aviso {
margin: 16px 0 0; font-size: 14px; color: var(--suave);
border: 1px dashed var(--borda); border-radius: var(--raio); padding: 14px 16px;
}
.aviso a { color: var(--destaque); font-weight: 600; }
.sobre { margin-top: 32px; }
.sobre h2 { margin-top: 0; }
.sobre dl { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; font-size: 14px; }
.sobre dt { color: var(--suave); }
.sobre dd { margin: 0; overflow-wrap: anywhere; }
.dica { font-size: 13px; color: var(--suave); margin: 14px 0 0; }
code { font-family: var(--mono); font-size: 0.92em; }
.rodape { margin-top: 32px; text-align: center; font-size: 13px; color: var(--suave); }
.rodape a { color: inherit; }
.so-leitor {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
@media (max-width: 480px) {
.pagina { padding-top: 32px; }
h1 { font-size: 24px; }
.formulario { flex-direction: column; }
.resultado { flex-direction: column; align-items: stretch; }
.sobre dl { grid-template-columns: 1fr; gap: 0; }
.sobre dd { margin-bottom: 8px; }
}
</style>
</head>
<body>
<main class="pagina">
<header class="topo">
<span class="marca" aria-hidden="true">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M10 14l4-4M8.5 11.5l-1.8 1.8a3.2 3.2 0 004.5 4.5l1.8-1.8M15.5 12.5l1.8-1.8a3.2 3.2 0 00-4.5-4.5l-1.8 1.8" />
</svg>
</span>
<h1>Encurtador de links</h1>
</header>
<p class="lead">Cole um link comprido e receba um endereço curto, pronto para compartilhar.</p>
<section class="cartao">
<form id="formulario" class="formulario" novalidate>
<label for="url" class="so-leitor">Link para encurtar</label>
<input id="url" name="url" type="url" inputmode="url" maxlength="2048" placeholder="Cole seu link aqui" autocomplete="off" required />
<button type="submit" id="encurtar">Encurtar</button>
</form>
<p id="erro" class="erro" role="alert" hidden></p>
<div id="resultado" class="resultado" hidden>
<a id="curto" href="#" target="_blank" rel="noopener"></a>
<button type="button" id="copiar" class="secundario">Copiar</button>
</div>
</section>
<h2>Últimos links</h2>
<section class="cartao">
<ul id="lista" class="lista"></ul>
<p id="vazio" class="vazio">Nenhum link ainda. Encurte o primeiro aí em cima.</p>
</section>
<p class="aviso">
Os links ficam na memória do app e somem quando ele é publicado de novo.
Para guardar os links de vez, <a href="https://app.dado.cloud/deploys" target="_blank" rel="noopener">ligue um Postgres</a>.
</p>
<section class="sobre cartao" aria-labelledby="sobre-titulo">
<h2 id="sobre-titulo">Sobre este deploy</h2>
<dl>
<dt>Runtime</dt>
<dd>{{RUNTIME}}</dd>
<dt>Região</dt>
<dd>Rodando em São Paulo</dd>
<dt>No ar desde</dt>
<dd><time datetime="{{INICIO_ISO}}">{{INICIO}}</time></dd>
<dt>Mensagem</dt>
<dd>{{MENSAGEM}}</dd>
</dl>
<p class="dica">
A mensagem vem da variável <code>MENSAGEM_BOAS_VINDAS</code>. Troque o valor nas
configurações do app, no painel, e publique de novo.
</p>
</section>
<footer class="rodape">Publicado na <a href="https://dado.cloud" target="_blank" rel="noopener">Dado</a></footer>
</main>
<script>
const formulario = document.getElementById('formulario');
const campo = document.getElementById('url');
const botao = document.getElementById('encurtar');
const erro = document.getElementById('erro');
const resultado = document.getElementById('resultado');
const curto = document.getElementById('curto');
const copiar = document.getElementById('copiar');
const lista = document.getElementById('lista');
const vazio = document.getElementById('vazio');
const semProtocolo = (url) => url.replace(/^https?:\/\//, '');
function itemDaLista(link) {
const li = document.createElement('li');
const info = document.createElement('div');
info.className = 'link-info';
const a = document.createElement('a');
a.href = link.curto;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = semProtocolo(link.curto);
const destino = document.createElement('span');
destino.className = 'destino';
destino.textContent = link.url;
destino.title = link.url;
info.append(a, destino);
const cliques = document.createElement('span');
cliques.className = 'cliques';
cliques.textContent = link.cliques === 1 ? '1 clique' : `${link.cliques} cliques`;
li.append(info, cliques);
return li;
}
async function carregarLinks() {
try {
const resposta = await fetch('/api/links', { cache: 'no-store' });
if (!resposta.ok) return;
const { links } = await resposta.json();
lista.replaceChildren(...links.map(itemDaLista));
vazio.hidden = links.length > 0;
} catch {
// Sem rede: a lista fica como estava.
}
}
function mostrarErro(mensagem) {
erro.textContent = mensagem;
erro.hidden = false;
}
formulario.addEventListener('submit', async (evento) => {
evento.preventDefault();
erro.hidden = true;
let url = campo.value.trim();
if (!url) return mostrarErro('Cole um link para encurtar.');
// Quem digita "exemplo.com.br" quer dizer https://exemplo.com.br.
if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) url = `https://${url}`;
botao.disabled = true;
try {
const resposta = await fetch('/api/links', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
});
const dados = await resposta.json().catch(() => ({}));
if (!resposta.ok) return mostrarErro(dados.erro || 'Não deu para encurtar esse link. Tente de novo.');
curto.href = dados.curto;
curto.textContent = semProtocolo(dados.curto);
copiar.textContent = 'Copiar';
resultado.hidden = false;
campo.value = '';
await carregarLinks();
} catch {
mostrarErro('Sem conexão com o servidor. Tente de novo.');
} finally {
botao.disabled = false;
}
});
copiar.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(curto.href);
copiar.textContent = 'Copiado!';
} catch {
// Navegador sem permissão de área de transferência: seleciona o link.
getSelection().selectAllChildren(curto);
}
});
// Voltou para a aba depois de testar um link? Atualiza a contagem de cliques.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') carregarLinks();
});
carregarLinks();
</script>
</body>
</html>
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Link não encontrado</title>
<style>
:root { color-scheme: light dark; }
body {
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: #f6f7f9; color: #14161a; line-height: 1.5;
}
main { max-width: 420px; text-align: center; }
h1 { font-size: 24px; margin: 0 0 8px; }
p { color: #5b6270; margin: 0 0 20px; }
a { color: #3b5bdb; font-weight: 600; }
@media (prefers-color-scheme: dark) {
body { background: #0f1115; color: #eceef2; }
p { color: #9aa1ad; }
a { color: #8299ff; }
}
</style>
</head>
<body>
<main>
<h1>Link não encontrado</h1>
<p>Esse link curto não existe ou sumiu quando o app foi publicado de novo.</p>
<a href="/">Encurtar um link</a>
</main>
</body>
</html>