Skip to content

Instantly share code, notes, and snippets.

@dragonde
Last active April 24, 2024 17:41
Show Gist options
  • Save dragonde/9b5def23a4b69a0dd247278b6775aabc to your computer and use it in GitHub Desktop.
Save dragonde/9b5def23a4b69a0dd247278b6775aabc to your computer and use it in GitHub Desktop.
little-program

hazme un pequeño programa que use rust, svelte y tailwind css ¡Vamos a crear algo emocionante!

Aquí te presento un ejemplo de aplicación simple que utiliza Rust como backend, Svelte como frontend y Tailwind CSS para estilizar la interfaz de usuario.

Backend (Rust)

use actix_web::{web, App, HttpResponse};
use serde::Deserialize;

#[derive(Deserialize)]
struct Greeting {
    name: String,
}

async fn greet(greeting: web::Path<Greeting>) -> HttpResponse {
    let name = greeting.name.clone();
    format!("¡Hola {}!", name).into()
}

#[actix_web] // ¡esto es el punto de entrada!
async fn main() {
    App::new().service(web::resource("/greet").route(web::get().to(greet)))App::new().service(web::resource("/greet").route(web::get().to(greet))).run("0.0.0:8080");
}

Este código define un servicio web que recibe una ruta /greet y devuelve un mensaje de bienvenida personalizado según el nombre proporcionado.

Frontend (Svelte)

<script>
  import { onMount } from 'sveltestrap';

  let name = '';

  onMount(() => {
    fetch('/greet', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    })
      .then((response) => response.json())
      .then((data) => (name = data));
  });

  function handleSubmit(event) {
    event.preventDefault();
    fetch('/greet', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name }),
    })
      .then((response) => response.json())
      .then((data) => (name = data));
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Escribe tu nombre:
        <input type="text" bind:value={name} />
      </label>
      <p>{`¡Hola ${name}!`}</p>
    </form>
  );
</script>

<style global>
  /* ¡Estilizar con Tailwind CSS! */
  form {
    @apply flex flex-col justify-center items-center p-4;
  }
  input[type="text"] {
    @apply w-full px-2 py-1;
  }
  label {
    @apply mb-2;
  }
</style>

Este código define una aplicación Svelte que consume el servicio web creado en Rust. La aplicación permite al usuario escribir su nombre y mostrar un mensaje de bienvenida personalizado.

Cómo ejecutar

Primero, asegúrate de tener instalado actix-web y serde en tu proyecto Rust mediante el comando:

cargo add actix-web serde

Luego, ejecuta el servicio web con el comando:

cargo run

Finalmente, abre un navegador y navega a http://localhost:8080/. Ahora puedes interactuar con la aplicación Svelte que se carga en el navegador.

¡Eso es todo! Espero que disfrutes creando algo nuevo con estos tres tecnologías.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment