basic/threading.rs
1use std::num::NonZeroU64;
2use std::thread;
3
4use afire::{Content, Method, Response, Server};
5
6use crate::Example;
7
8// You can run this example with `cargo run --example basic -- threading`
9
10// Create a new basic server like in example 01
11// However, we want to use a thread pool to handle the requests
12
13// In production, you would probably want to use a reverse proxy like nginx
14// or something similar to split the load across multiple servers if you have a lot of traffic
15// But just a thread pool is a good way to get started
16
17pub struct Threading;
18
19impl Example for Threading {
20 fn name(&self) -> &'static str {
21 "threading"
22 }
23
24 fn exec(&self) {
25 // Create a new Server instance on localhost port 8080
26 let mut server = Server::<()>::new("localhost", 8080);
27
28 // Define a handler for GET "/"
29 server.route(Method::GET, "/", |_req| {
30 Response::new()
31 // hopefully the ThreadId.as_u64 method will become stable
32 // until then im stuck with this mess for the example
33 // It just gets the thread ID to show the user what thread is handling the request
34 .text(format!(
35 "Hello from thread number {:#?}!",
36 unsafe { std::mem::transmute::<_, NonZeroU64>(thread::current().id()) }.get()
37 - 1
38 ))
39 .content(Content::TXT)
40 });
41
42 // Start the server with 8 threads
43 // This will block the current thread
44 server.start_threaded(8).unwrap();
45
46 // If you go to http://localhost:8080 you should see the thread ID change with each refresh
47 }
48}