Last active
May 18, 2019 09:36
-
-
Save TatriX/65690794de1e7b974605342b74a470b7 to your computer and use it in GitHub Desktop.
TcpStream & fetch example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
</head> | |
<body> | |
<script> | |
fetch("/img").then(res => res.blob()) | |
.then(blob => { | |
const img = new Image(); | |
img.src = URL.createObjectURL(blob); | |
document.body.appendChild(img); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{self, Write, Read}; | |
use std::net::{TcpListener, TcpStream}; | |
use std::fs::File; | |
fn handle_client(mut stream: TcpStream) { | |
let file = File::open("logo.png").unwrap(); | |
let bytes = file.bytes().collect::<io::Result<Vec<_>>>().unwrap(); | |
write!(stream, "HTTP/1.1 200 OK\r\n").unwrap(); | |
write!(stream, "Content-Type: image/png\r\n").unwrap(); | |
write!(stream, "Content-Length: {}\r\n", bytes.len()).unwrap(); | |
write!(stream, "\r\n").unwrap(); | |
stream.write(&bytes).unwrap(); | |
} | |
fn main() -> io::Result<()> { | |
let listener = TcpListener::bind("127.0.0.1:34254")?; | |
// accept connections and process them serially | |
for stream in listener.incoming() { | |
handle_client(stream?); | |
} | |
Ok(()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
listen 8888; | |
root /tmp/tcp-image; | |
location / { | |
index index.html index.htm; | |
} | |
location /img { | |
proxy_pass http://127.0.0.1:34254; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment