Skip to content

Commit 5886cf7

Browse files
committed
error処理を簡素化
1 parent 32d6c34 commit 5886cf7

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

chapter2/src/2_4_4/server.rs

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,40 @@
11
use std::net::{TcpStream, TcpListener};
22
use std::io::{Write, BufReader, BufRead};
33

4-
fn get_operation(stream: &mut TcpStream) {
4+
fn get_operation(stream: &mut TcpStream) -> std::io::Result<()> {
55
let body = "HTTP server sample";
6-
writeln!(stream, "HTTP/1.1 200 OK").unwrap();
7-
writeln!(stream, "Content-Type: text/html; charset=UTF-8").unwrap();
8-
writeln!(stream, "Content-Length: {}", body.len()).unwrap();
9-
writeln!(stream).unwrap();
6+
writeln!(stream, "HTTP/1.1 200 OK")?;
7+
writeln!(stream, "Content-Type: text/plain; charset=UTF-8")?;
8+
writeln!(stream, "Content-Length: {}", body.len())?;
9+
writeln!(stream)?;
1010

11-
writeln!(stream, "{}", body).unwrap();
11+
writeln!(stream, "{}", body)?;
12+
Ok(())
1213
}
1314

14-
fn handle_client(stream: TcpStream) {
15+
fn handle_client(stream: TcpStream) -> std::io::Result<()> {
1516
let mut reader = BufReader::new(stream);
1617

1718
let mut first_line = String::new();
18-
if let Err(err) = reader.read_line(&mut first_line) {
19-
panic!("error during receive a line: {}", err);
20-
}
19+
reader.read_line(&mut first_line)?;
2120

2221
let mut params = first_line.split_whitespace();
2322
let method = params.next();
2423
let path = params.next();
2524
match (method, path) {
2625
(Some("GET"), Some(_)) => {
27-
get_operation(reader.get_mut());
26+
get_operation(reader.get_mut())?;
2827
}
2928
_ => panic!("failed to parse"),
3029
}
30+
Ok(())
3131
}
3232

33-
fn main() {
34-
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
33+
fn main() -> std::io::Result<()> {
34+
let listener = TcpListener::bind("127.0.0.1:8080")?;
3535

3636
for stream in listener.incoming() {
37-
match stream {
38-
Ok(stream) => {
39-
handle_client(stream)
40-
}
41-
Err(_) => { panic!("connection failed") }
42-
};
37+
handle_client(stream?)?;
4338
}
39+
Ok(())
4440
}

0 commit comments

Comments
 (0)