Skip to content

Commit 704256b

Browse files
committed
set request url host from host header
1 parent c1780d6 commit 704256b

File tree

4 files changed

+40
-4
lines changed

4 files changed

+40
-4
lines changed

src/server/decode.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::str::FromStr;
55
use async_std::io::BufReader;
66
use async_std::io::Read;
77
use async_std::prelude::*;
8-
use http_types::headers::{HeaderName, HeaderValue, CONTENT_LENGTH, TRANSFER_ENCODING};
8+
use http_types::headers::{HeaderName, HeaderValue, CONTENT_LENGTH, HOST, TRANSFER_ENCODING};
99
use http_types::{ensure, ensure_eq, format_err};
1010
use http_types::{Body, Method, Request};
1111

@@ -57,9 +57,9 @@ where
5757
let method = httparse_req.method;
5858
let method = method.ok_or_else(|| format_err!("No method found"))?;
5959

60-
let uri = httparse_req.path;
61-
let uri = uri.ok_or_else(|| format_err!("No uri found"))?;
62-
let uri = url::Url::parse(&format!("{}{}", addr, uri))?;
60+
let path = httparse_req.path;
61+
let path = path.ok_or_else(|| format_err!("No uri found"))?;
62+
let uri = url::Url::parse(&format!("{}{}", addr, path))?;
6363

6464
let version = httparse_req.version;
6565
let version = version.ok_or_else(|| format_err!("No version found"))?;
@@ -72,6 +72,12 @@ where
7272
req.insert_header(name, value)?;
7373
}
7474

75+
if let Some(host) = req.header(&HOST).cloned() {
76+
if let Some(host) = host.last() {
77+
*req.url_mut() = url::Url::parse(&format!("http://{}{}", host, path))?;
78+
}
79+
}
80+
7581
let content_length = req.header(&CONTENT_LENGTH);
7682
let transfer_encoding = req.header(&TRANSFER_ENCODING);
7783

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
GET /pub/WWW/TheProject.html HTTP/1.1
2+
Host: www.w3.org
3+
Content-Length: 0
4+
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
HTTP/1.1 200 OK
2+
content-length: 41
3+
date: {DATE}
4+
content-type: text/plain; charset=utf-8
5+
6+
http://www.w3.org/pub/WWW/TheProject.html

tests/server.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,26 @@ async fn test_basic_request() {
2525
case.assert().await;
2626
}
2727

28+
#[async_std::test]
29+
async fn test_host() {
30+
let case = TestCase::new_server(
31+
"fixtures/request-with-host.txt",
32+
"fixtures/response-with-host.txt",
33+
)
34+
.await;
35+
let addr = "http://127.0.0.1:8000";
36+
37+
async_h1::accept(addr, case.clone(), |req| async move {
38+
let mut res = Response::new(StatusCode::Ok);
39+
res.set_body(req.url().as_str());
40+
Ok(res)
41+
})
42+
.await
43+
.unwrap();
44+
45+
case.assert().await;
46+
}
47+
2848
#[async_std::test]
2949
async fn test_chunked_basic() {
3050
let case = TestCase::new_server(

0 commit comments

Comments
 (0)