Rust开发实现基本的入门练习——HTTP服务器

环境:rust + IDEA

main.rs

//引入外部文件
mod mod_hello;
mod mod_http;
pub use self::mod_hello::*;
pub use self::mod_http::*;
//
use std::io;


#[derive(Debug)]
struct User {
    username: String,
    age: i32
}

fn main() {
    println!("Hello, world!");
    println!("{:X} {1} {0}", 10, 11);

    let zhang = User {
        username: String::from("zhangsan"),
        age: 28
    };
    println!("{:#?} \n{:p}", zhang, &zhang);

    //元祖
    let x = (345,"hhhh");
    let y:(i32,&str) = (123,"hello");
    println!("{} {}", x.1, y.0);

    //String::new()
    //#[warn(unused_mut)]
    let mut guess= String::from("hello rust");
    print!("{}\n", guess);

    //读取命令行
    //#[warn(unused_imports)]
    //io::stdin().read_line(&mut guess).expect("failed to read line");
    //println!("{}", guess);

    //引用外部函数
    hello();
    //当前模块路径
    println!(module_path!());

    //创建http server
    http_main();
}

mod_http.rs

//引用系统包
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::fs::File;
use std::thread;
use std::alloc::handle_alloc_error;

pub fn http_main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(||{
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    let get = b"GET / HTTP/1.1\r\n";
    //逻辑处理
    let (status_line,filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };

    //创建Body
    let mut file = File::open(filename).unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    let response = format!("{}{}", status_line, contents);
    //流写入Body
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

//参考:https://www.jianshu.com/p/143fe4134615

mod_hello.rs


//引用mod上的结构体
use super::User;

//外部可以使用
pub fn hello() {
    println!("hello in file demo");
    let lisi = User {
        username: String::from("Lisi"),
        age: 30
    };
    println!("{:#?}", lisi);
}

运行结果:

Rust开发实现基本的入门练习——HTTP服务器_第1张图片

Rust开发实现基本的入门练习——HTTP服务器_第2张图片

加油,继续研究!

你可能感兴趣的:(编程经验)