Learning rust – guess number code

Why rust?
– Fast
– Reliable
– Deep WASM integration
https://aws.amazon.com/blogs/opensource/sustainability-with-rust/

use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number:");
    let secret_number = rand::thread_rng().gen_range(1..101);
    loop {

    
    println!("Please input your guess.");
    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("fail to read line");

    
    let guess: u32 = match guess.trim().parse() {
        Ok(num) => num,
        Err(_) => continue,
    };
    println!("You guess : {}",guess);
    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        }
    }
    }
}
  • It calls main function by default.
  • can accept parameter in ()
  • &mut guess uses reference rather value

Want to get started with Rust?

https://doc.rust-lang.org/book/title-page.html

Create statically linked rust docker image with alpine

Why?
– Optimize size
– less surface attack

FROM rust:slim-buster AS build
WORKDIR /opt
COPY . .
RUN rustup target add x86_64-unknown-linux-musl
RUN cargo build --target x86_64-unknown-linux-musl --release

FROM alpine:3.15.0
WORKDIR /opt
COPY --from=build /opt/target/x86_64-unknown-linux-musl/release .
EXPOSE 7878
CMD ["/opt/simple-rust-webserver"]
docker build -t rust-web-alpine -f alpine.Dockerfile .

docker run -d -p 7878:7878 rust-web-alpine
[root@lp-test-1 simple-rust-webserver]# docker images | grep rust-web-alpine
rust-web-alpine                                latest          7dd00663078c   9 minutes ago    9.4MB

main.rs

use std::net::{TcpStream, TcpListener};
use std::io::{Read, Write};
use std::thread;


fn handle_read(mut stream: &TcpStream) {
    let mut buf = [0u8 ;4096];
    match stream.read(&mut buf) {
        Ok(_) => {
            let req_str = String::from_utf8_lossy(&buf);
            println!("{}", req_str);
            },
        Err(e) => println!("Unable to read stream: {}", e),
    }
}

fn handle_write(mut stream: TcpStream) {
    let response = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>hola rust</body></html>\r\n";
    match stream.write(response) {
        Ok(_) => println!("Response sent"),
        Err(e) => println!("Failed sending response: {}", e),
    }
}

fn handle_client(stream: TcpStream) {
    handle_read(&stream);
    handle_write(stream);
}

fn main() {
    let listener = TcpListener::bind("0.0.0.0:7878").unwrap();
    println!("Listening for connections on port {}", 7878);

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(|| {
                    handle_client(stream)
                });
            }
            Err(e) => {
                println!("Unable to connect: {}", e);
            }
        }
    }
}

More : https://users.rust-lang.org/t/building-executable-for-alpine-linux/13568

https://doc.rust-lang.org/cargo/commands/cargo-build.html