whoareu

  • 90 Posts
  • 760 Comments
Joined 2 years ago
cake
Cake day: June 4th, 2023

help-circle



















  • yeah, you are right, I don’t need mut. here is the improved version:

    use axum::{extract::Path, routing::get, routing::post, Router};
    use std::fs::{read_to_string, File};
    use std::io::prelude::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    
    const MAX_FILE_SIZE: usize = 1024 * 1024 * 10;
    static FILE_COUNT: AtomicUsize = AtomicUsize::new(0);
    
    async fn handle(Path(id): Path<String>) -> String {
        match read_to_string(id) {
            Ok(content) => content,
            Err(e) => e.to_string(),
        }
    }
    
    async fn submit_handle(bytes: String) -> String {
        dbg!(&bytes);
        if bytes.len() > MAX_FILE_SIZE {
            // Don't store the file if it exceeds max size
            return String::from("ERROR: max size exceeded");
        }
        let path = FILE_COUNT.load(Ordering::Relaxed);
        FILE_COUNT.fetch_add(1, Ordering::SeqCst);
        let mut output = File::create(path.to_string()).unwrap();
        write!(output, "{}", bytes).unwrap();
        let mut url = String::from("http://localhost:3000/");
        url.push_str(&path.to_string());
        return url;
    }
    
    #[tokio::main]
    async fn main() {
        let app = Router::new()
            .route("/", get(|| async { "Paste something in pastebin! use curl -X POST http://localhost:3000/submit -d 'this is some data'" }))
            .route("/{id}", get(handle))
            .route("/submit", post(submit_handle));
    
        let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
            .await
            .unwrap();
        axum::serve(listener, app).await.unwrap();
    }
    
    





















Moderates