Skip to content

Commit c564909

Browse files
authored
Implement redirect (#5) (#30)
1 parent c162ae6 commit c564909

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

python/http.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def _get_headers_and_body(sock, host, port, path):
6262
version, status, explanation = line.split(" ", 2)
6363

6464
# 9. Check status
65-
assert status == "200", f"{status}: {explanation}"
65+
assert status in ("200", "301", "302"), f"{status}: {explanation}"
6666

6767
# 10. Parse headers
6868
headers = {}
@@ -73,6 +73,9 @@ def _get_headers_and_body(sock, host, port, path):
7373
header, value = line.split(":", 1)
7474
headers[header.lower()] = value.strip()
7575

76+
if "location" in headers:
77+
return request(headers["location"])
78+
7679
if "transfer-encoding" in headers:
7780
encoding = headers["transfer-encoding"]
7881
if encoding == "chunked":

python/tests/test_http.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@ def test_lex(self):
3232
ret = lex(origin)
3333
self.assertEqual(ret, " test ")
3434

35+
def test_redirect(self):
36+
redirect_sites = [
37+
"http://www.naver.com/",
38+
"http://browser.engineering/redirect",
39+
]
40+
for site in redirect_sites:
41+
headers, body = request(site)
42+
self.assertGreater(len(body), 0)
43+
self.assertIn("content-type", headers)
44+
3545

3646
if __name__ == "__main__":
3747
unittest.main()

rust/src/lib.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ pub mod http {
180180

181181
// 9. Check status
182182
match status {
183-
"200" => (),
183+
"200" | "301" | "302" => (),
184184
_ => panic!("{}: {}", status, explanation),
185185
};
186186

@@ -200,6 +200,10 @@ pub mod http {
200200
headers.insert(header, value.to_string());
201201
}
202202

203+
if let Some(url) = headers.get("location") {
204+
return request(url);
205+
}
206+
203207
let content_encoding: ContentEncoding = match headers.get("content-encoding") {
204208
Some(encoding) => encoding.parse().map_err(|_| UNSUPPORTED_ENCODING)?,
205209
None => ContentEncoding::Identity,
@@ -447,4 +451,18 @@ mod tests {
447451
assert_eq!(http::lex(origin.as_bytes()), " test ");
448452
Ok(())
449453
}
454+
455+
#[test]
456+
fn test_redirect() -> Result<(), String> {
457+
let redirect_sites = vec![
458+
"http://www.naver.com/",
459+
"http://browser.engineering/redirect",
460+
];
461+
for site in redirect_sites {
462+
let (header, body) = http::request(site).unwrap();
463+
assert!(header.contains_key("content-type"));
464+
assert!(!body.is_empty());
465+
}
466+
Ok(())
467+
}
450468
}

0 commit comments

Comments
 (0)