pub struct WebUIConfig {
pub port: u16,
pub host: [u8; 4],
pub title: String,
pub static_dir: String,
}Expand description
Configuration for the WebUI server.
This struct contains all the settings needed to configure and run the web server, including network settings, UI customization, and file serving options.
§Examples
use web_ui::WebUIConfig;
let config = WebUIConfig::default()
.with_port(8080)
.with_host([0, 0, 0, 0]) // Listen on all interfaces
.with_title("My Application".to_string())
.with_static_dir("./public".to_string());Fields§
§port: u16Port number to bind the server to
host: [u8; 4]Host IP address as a 4-byte array [a, b, c, d]
title: StringTitle of the web application (used in HTML title tag)
static_dir: StringDirectory path containing static files to serve
Implementations§
Source§impl WebUIConfig
impl WebUIConfig
Sourcepub fn with_port(self, port: u16) -> Self
pub fn with_port(self, port: u16) -> Self
Sets the port number for the server.
§Arguments
port- The port number to bind to (1-65535)
§Examples
use web_ui::WebUIConfig;
let config = WebUIConfig::default().with_port(8080);Examples found in repository?
More examples
examples/event_binding.rs (line 9)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration
8 let config = WebUIConfig::default()
9 .with_port(3030)
10 .with_title("Event Binding Demo".to_string())
11 .with_static_dir("./static/event_binding".to_string());
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Shared counter for demonstrating state
17 let click_counter = Arc::new(AtomicU32::new(0));
18
19 // Bind a simple hello button
20 web_ui.bind_click("hello-btn", || {
21 println!("Hello button was clicked!");
22 }).await;
23
24 // Bind a counter button with state and response data
25 let counter_clone = click_counter.clone();
26 web_ui.bind_event("count-btn", "click", move |_event| {
27 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28 println!("Count button clicked {} times", count);
29
30 Ok(UIResponse {
31 success: true,
32 message: Some(format!("Button clicked {} times", count)),
33 data: Some(serde_json::json!({ "count": count })),
34 request_id: None,
35 })
36 }).await;
37
38 // Bind a greeting button that uses input data
39 web_ui.bind_event("greet-btn", "click", |event| {
40 println!("Greet button event data: {:?}", event.data);
41
42 // Try to get the name from the input field
43 let name = if let Some(name_value) = event.data.get("name-input") {
44 name_value.as_str().unwrap_or("Anonymous")
45 } else {
46 // If not provided in event data, we'll need to handle it differently
47 "Friend"
48 };
49
50 let greeting = format!("Hello, {}! Nice to meet you.", name);
51 println!("Greeting: {}", greeting);
52
53 Ok(UIResponse {
54 success: true,
55 message: Some(greeting),
56 data: Some(serde_json::json!({
57 "greeting_sent": true,
58 "name": name
59 })),
60 request_id: None,
61 })
62 }).await;
63
64 // Bind input change events for real-time updates
65 web_ui.bind_event("name-input", "change", |event| {
66 if let Some(value) = event.data.get("value") {
67 if let Some(name) = value.as_str() {
68 println!("Name input changed to: {}", name);
69 return Ok(UIResponse {
70 success: true,
71 message: Some(format!("Name updated to: {}", name)),
72 data: None,
73 request_id: None,
74 });
75 }
76 }
77
78 Ok(UIResponse {
79 success: true,
80 message: Some("Name input changed".to_string()),
81 data: None,
82 request_id: None,
83 })
84 }).await;
85
86 println!("Starting Web UI server...");
87 println!("Visit http://localhost:3030 to see the demo");
88 println!("Try clicking the buttons to see the event binding in action!");
89
90 // Start the server
91 web_ui.run().await
92}template/template.rs (line 9)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration for your web UI
8 let config = WebUIConfig::default()
9 .with_port(3030) // Change this port if needed
10 .with_title("Your Web UI Component".to_string()) // Customize your title
11 .with_static_dir("./template/static".to_string()); // Point to your static files directory
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Example: Shared state (optional)
17 let counter = Arc::new(AtomicU32::new(0));
18
19 // Example 1: Simple button click handler
20 web_ui.bind_click("your-button-id", || {
21 println!("Button was clicked!");
22 // Add your custom logic here
23 }).await;
24
25 // Example 2: Event handler with response data
26 let counter_clone = counter.clone();
27 web_ui.bind_event("your-button-id", "click", move |event| {
28 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
29 println!("Event received: {:?}", event);
30
31 // Return a response to the client
32 Ok(UIResponse {
33 success: true,
34 message: Some(format!("Action completed successfully! Count: {}", count)),
35 data: Some(serde_json::json!({
36 "count": count,
37 })),
38 request_id: event.request_id,
39 })
40 }).await;
41
42 // Example 3: Input field handler
43 web_ui.bind_event("your-input-id", "change", |event| {
44 println!("Input changed: {:?}", event.data);
45
46 // Process input data
47 let input_value = event.data.get("value")
48 .and_then(|v| v.as_str())
49 .unwrap_or("");
50
51 Ok(UIResponse {
52 success: true,
53 message: Some(format!("Input received: {}", input_value)),
54 data: Some(serde_json::json!({ "processed_input": input_value.to_uppercase() })),
55 request_id: event.request_id,
56 })
57 }).await;
58
59 // Example 4: Form submission handler
60 web_ui.bind_event("your-form-id", "submit", |event| {
61 println!("Form submitted: {:?}", event.data);
62
63 // Extract form data from the formData object
64 let form_data = event.data.get("formData")
65 .and_then(|v| v.as_object());
66
67 let name = form_data
68 .and_then(|fd| fd.get("name"))
69 .and_then(|v| v.as_str())
70 .unwrap_or("Unknown");
71
72 let email = form_data
73 .and_then(|fd| fd.get("email"))
74 .and_then(|v| v.as_str())
75 .unwrap_or("No email provided");
76
77 // Process form data here
78 // You can validate, save to database, send emails, etc.
79
80 Ok(UIResponse {
81 success: true,
82 message: Some(format!("Thank you, {}! Form submitted successfully.", name)),
83 data: Some(serde_json::json!({
84 "user_name": name,
85 "user_email": email,
86 })),
87 request_id: event.request_id,
88 })
89 }).await;
90
91 // Example 5: Custom event with error handling
92 web_ui.bind_event("custom-action", "custom", |event| {
93 println!("Custom event received: {:?}", event);
94
95 // Simulate some processing that might fail
96 let data = event.data.get("required_field");
97
98 if data.is_none() {
99 return Ok(UIResponse {
100 success: false,
101 message: Some("Required field is missing".to_string()),
102 data: None,
103 request_id: event.request_id,
104 });
105 }
106
107 // Process the data...
108
109 Ok(UIResponse {
110 success: true,
111 message: Some("Custom action completed".to_string()),
112 data: Some(serde_json::json!({ "result": "success" })),
113 request_id: event.request_id,
114 })
115 }).await;
116
117 // Start the web server
118 println!("Starting web UI server on http://localhost:3030");
119 web_ui.run().await?;
120
121 Ok(())
122}Sourcepub fn with_title(self, title: String) -> Self
pub fn with_title(self, title: String) -> Self
Sets the title of the web application.
§Arguments
title- The title string to use in the HTML title tag
§Examples
use web_ui::WebUIConfig;
let config = WebUIConfig::default().with_title("My App".to_string());Examples found in repository?
More examples
examples/event_binding.rs (line 10)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration
8 let config = WebUIConfig::default()
9 .with_port(3030)
10 .with_title("Event Binding Demo".to_string())
11 .with_static_dir("./static/event_binding".to_string());
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Shared counter for demonstrating state
17 let click_counter = Arc::new(AtomicU32::new(0));
18
19 // Bind a simple hello button
20 web_ui.bind_click("hello-btn", || {
21 println!("Hello button was clicked!");
22 }).await;
23
24 // Bind a counter button with state and response data
25 let counter_clone = click_counter.clone();
26 web_ui.bind_event("count-btn", "click", move |_event| {
27 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28 println!("Count button clicked {} times", count);
29
30 Ok(UIResponse {
31 success: true,
32 message: Some(format!("Button clicked {} times", count)),
33 data: Some(serde_json::json!({ "count": count })),
34 request_id: None,
35 })
36 }).await;
37
38 // Bind a greeting button that uses input data
39 web_ui.bind_event("greet-btn", "click", |event| {
40 println!("Greet button event data: {:?}", event.data);
41
42 // Try to get the name from the input field
43 let name = if let Some(name_value) = event.data.get("name-input") {
44 name_value.as_str().unwrap_or("Anonymous")
45 } else {
46 // If not provided in event data, we'll need to handle it differently
47 "Friend"
48 };
49
50 let greeting = format!("Hello, {}! Nice to meet you.", name);
51 println!("Greeting: {}", greeting);
52
53 Ok(UIResponse {
54 success: true,
55 message: Some(greeting),
56 data: Some(serde_json::json!({
57 "greeting_sent": true,
58 "name": name
59 })),
60 request_id: None,
61 })
62 }).await;
63
64 // Bind input change events for real-time updates
65 web_ui.bind_event("name-input", "change", |event| {
66 if let Some(value) = event.data.get("value") {
67 if let Some(name) = value.as_str() {
68 println!("Name input changed to: {}", name);
69 return Ok(UIResponse {
70 success: true,
71 message: Some(format!("Name updated to: {}", name)),
72 data: None,
73 request_id: None,
74 });
75 }
76 }
77
78 Ok(UIResponse {
79 success: true,
80 message: Some("Name input changed".to_string()),
81 data: None,
82 request_id: None,
83 })
84 }).await;
85
86 println!("Starting Web UI server...");
87 println!("Visit http://localhost:3030 to see the demo");
88 println!("Try clicking the buttons to see the event binding in action!");
89
90 // Start the server
91 web_ui.run().await
92}template/template.rs (line 10)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration for your web UI
8 let config = WebUIConfig::default()
9 .with_port(3030) // Change this port if needed
10 .with_title("Your Web UI Component".to_string()) // Customize your title
11 .with_static_dir("./template/static".to_string()); // Point to your static files directory
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Example: Shared state (optional)
17 let counter = Arc::new(AtomicU32::new(0));
18
19 // Example 1: Simple button click handler
20 web_ui.bind_click("your-button-id", || {
21 println!("Button was clicked!");
22 // Add your custom logic here
23 }).await;
24
25 // Example 2: Event handler with response data
26 let counter_clone = counter.clone();
27 web_ui.bind_event("your-button-id", "click", move |event| {
28 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
29 println!("Event received: {:?}", event);
30
31 // Return a response to the client
32 Ok(UIResponse {
33 success: true,
34 message: Some(format!("Action completed successfully! Count: {}", count)),
35 data: Some(serde_json::json!({
36 "count": count,
37 })),
38 request_id: event.request_id,
39 })
40 }).await;
41
42 // Example 3: Input field handler
43 web_ui.bind_event("your-input-id", "change", |event| {
44 println!("Input changed: {:?}", event.data);
45
46 // Process input data
47 let input_value = event.data.get("value")
48 .and_then(|v| v.as_str())
49 .unwrap_or("");
50
51 Ok(UIResponse {
52 success: true,
53 message: Some(format!("Input received: {}", input_value)),
54 data: Some(serde_json::json!({ "processed_input": input_value.to_uppercase() })),
55 request_id: event.request_id,
56 })
57 }).await;
58
59 // Example 4: Form submission handler
60 web_ui.bind_event("your-form-id", "submit", |event| {
61 println!("Form submitted: {:?}", event.data);
62
63 // Extract form data from the formData object
64 let form_data = event.data.get("formData")
65 .and_then(|v| v.as_object());
66
67 let name = form_data
68 .and_then(|fd| fd.get("name"))
69 .and_then(|v| v.as_str())
70 .unwrap_or("Unknown");
71
72 let email = form_data
73 .and_then(|fd| fd.get("email"))
74 .and_then(|v| v.as_str())
75 .unwrap_or("No email provided");
76
77 // Process form data here
78 // You can validate, save to database, send emails, etc.
79
80 Ok(UIResponse {
81 success: true,
82 message: Some(format!("Thank you, {}! Form submitted successfully.", name)),
83 data: Some(serde_json::json!({
84 "user_name": name,
85 "user_email": email,
86 })),
87 request_id: event.request_id,
88 })
89 }).await;
90
91 // Example 5: Custom event with error handling
92 web_ui.bind_event("custom-action", "custom", |event| {
93 println!("Custom event received: {:?}", event);
94
95 // Simulate some processing that might fail
96 let data = event.data.get("required_field");
97
98 if data.is_none() {
99 return Ok(UIResponse {
100 success: false,
101 message: Some("Required field is missing".to_string()),
102 data: None,
103 request_id: event.request_id,
104 });
105 }
106
107 // Process the data...
108
109 Ok(UIResponse {
110 success: true,
111 message: Some("Custom action completed".to_string()),
112 data: Some(serde_json::json!({ "result": "success" })),
113 request_id: event.request_id,
114 })
115 }).await;
116
117 // Start the web server
118 println!("Starting web UI server on http://localhost:3030");
119 web_ui.run().await?;
120
121 Ok(())
122}Sourcepub fn with_static_dir(self, static_dir: String) -> Self
pub fn with_static_dir(self, static_dir: String) -> Self
Sets the directory path for serving static files.
§Arguments
static_dir- Path to the directory containing static files
§Examples
use web_ui::WebUIConfig;
let config = WebUIConfig::default().with_static_dir("./public".to_string());Examples found in repository?
More examples
examples/hello.rs (line 6)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5 let config = WebUIConfig::default()
6 .with_static_dir("./static/hello".to_string());
7 let web_ui = WebUI::new(config);
8
9 // Simple button click handler
10 web_ui.bind_click("hello-btn", || {
11 println!("Hello, World!");
12 }).await;
13
14 println!("Starting simple web UI on http://localhost:3030");
15 web_ui.run().await
16}examples/event_binding.rs (line 11)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration
8 let config = WebUIConfig::default()
9 .with_port(3030)
10 .with_title("Event Binding Demo".to_string())
11 .with_static_dir("./static/event_binding".to_string());
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Shared counter for demonstrating state
17 let click_counter = Arc::new(AtomicU32::new(0));
18
19 // Bind a simple hello button
20 web_ui.bind_click("hello-btn", || {
21 println!("Hello button was clicked!");
22 }).await;
23
24 // Bind a counter button with state and response data
25 let counter_clone = click_counter.clone();
26 web_ui.bind_event("count-btn", "click", move |_event| {
27 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28 println!("Count button clicked {} times", count);
29
30 Ok(UIResponse {
31 success: true,
32 message: Some(format!("Button clicked {} times", count)),
33 data: Some(serde_json::json!({ "count": count })),
34 request_id: None,
35 })
36 }).await;
37
38 // Bind a greeting button that uses input data
39 web_ui.bind_event("greet-btn", "click", |event| {
40 println!("Greet button event data: {:?}", event.data);
41
42 // Try to get the name from the input field
43 let name = if let Some(name_value) = event.data.get("name-input") {
44 name_value.as_str().unwrap_or("Anonymous")
45 } else {
46 // If not provided in event data, we'll need to handle it differently
47 "Friend"
48 };
49
50 let greeting = format!("Hello, {}! Nice to meet you.", name);
51 println!("Greeting: {}", greeting);
52
53 Ok(UIResponse {
54 success: true,
55 message: Some(greeting),
56 data: Some(serde_json::json!({
57 "greeting_sent": true,
58 "name": name
59 })),
60 request_id: None,
61 })
62 }).await;
63
64 // Bind input change events for real-time updates
65 web_ui.bind_event("name-input", "change", |event| {
66 if let Some(value) = event.data.get("value") {
67 if let Some(name) = value.as_str() {
68 println!("Name input changed to: {}", name);
69 return Ok(UIResponse {
70 success: true,
71 message: Some(format!("Name updated to: {}", name)),
72 data: None,
73 request_id: None,
74 });
75 }
76 }
77
78 Ok(UIResponse {
79 success: true,
80 message: Some("Name input changed".to_string()),
81 data: None,
82 request_id: None,
83 })
84 }).await;
85
86 println!("Starting Web UI server...");
87 println!("Visit http://localhost:3030 to see the demo");
88 println!("Try clicking the buttons to see the event binding in action!");
89
90 // Start the server
91 web_ui.run().await
92}template/template.rs (line 11)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7 // Create configuration for your web UI
8 let config = WebUIConfig::default()
9 .with_port(3030) // Change this port if needed
10 .with_title("Your Web UI Component".to_string()) // Customize your title
11 .with_static_dir("./template/static".to_string()); // Point to your static files directory
12
13 // Create WebUI instance
14 let web_ui = WebUI::new(config);
15
16 // Example: Shared state (optional)
17 let counter = Arc::new(AtomicU32::new(0));
18
19 // Example 1: Simple button click handler
20 web_ui.bind_click("your-button-id", || {
21 println!("Button was clicked!");
22 // Add your custom logic here
23 }).await;
24
25 // Example 2: Event handler with response data
26 let counter_clone = counter.clone();
27 web_ui.bind_event("your-button-id", "click", move |event| {
28 let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
29 println!("Event received: {:?}", event);
30
31 // Return a response to the client
32 Ok(UIResponse {
33 success: true,
34 message: Some(format!("Action completed successfully! Count: {}", count)),
35 data: Some(serde_json::json!({
36 "count": count,
37 })),
38 request_id: event.request_id,
39 })
40 }).await;
41
42 // Example 3: Input field handler
43 web_ui.bind_event("your-input-id", "change", |event| {
44 println!("Input changed: {:?}", event.data);
45
46 // Process input data
47 let input_value = event.data.get("value")
48 .and_then(|v| v.as_str())
49 .unwrap_or("");
50
51 Ok(UIResponse {
52 success: true,
53 message: Some(format!("Input received: {}", input_value)),
54 data: Some(serde_json::json!({ "processed_input": input_value.to_uppercase() })),
55 request_id: event.request_id,
56 })
57 }).await;
58
59 // Example 4: Form submission handler
60 web_ui.bind_event("your-form-id", "submit", |event| {
61 println!("Form submitted: {:?}", event.data);
62
63 // Extract form data from the formData object
64 let form_data = event.data.get("formData")
65 .and_then(|v| v.as_object());
66
67 let name = form_data
68 .and_then(|fd| fd.get("name"))
69 .and_then(|v| v.as_str())
70 .unwrap_or("Unknown");
71
72 let email = form_data
73 .and_then(|fd| fd.get("email"))
74 .and_then(|v| v.as_str())
75 .unwrap_or("No email provided");
76
77 // Process form data here
78 // You can validate, save to database, send emails, etc.
79
80 Ok(UIResponse {
81 success: true,
82 message: Some(format!("Thank you, {}! Form submitted successfully.", name)),
83 data: Some(serde_json::json!({
84 "user_name": name,
85 "user_email": email,
86 })),
87 request_id: event.request_id,
88 })
89 }).await;
90
91 // Example 5: Custom event with error handling
92 web_ui.bind_event("custom-action", "custom", |event| {
93 println!("Custom event received: {:?}", event);
94
95 // Simulate some processing that might fail
96 let data = event.data.get("required_field");
97
98 if data.is_none() {
99 return Ok(UIResponse {
100 success: false,
101 message: Some("Required field is missing".to_string()),
102 data: None,
103 request_id: event.request_id,
104 });
105 }
106
107 // Process the data...
108
109 Ok(UIResponse {
110 success: true,
111 message: Some("Custom action completed".to_string()),
112 data: Some(serde_json::json!({ "result": "success" })),
113 request_id: event.request_id,
114 })
115 }).await;
116
117 // Start the web server
118 println!("Starting web UI server on http://localhost:3030");
119 web_ui.run().await?;
120
121 Ok(())
122}Trait Implementations§
Auto Trait Implementations§
impl Freeze for WebUIConfig
impl RefUnwindSafe for WebUIConfig
impl Send for WebUIConfig
impl Sync for WebUIConfig
impl Unpin for WebUIConfig
impl UnwindSafe for WebUIConfig
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more