-
-
Save RandyMcMillan/b94bbf78a3d809ed860fbd8f5f44a936 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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::fmt; | |
use std::net::{TcpStream, SocketAddr, ToSocketAddrs}; | |
use std::io::prelude::*; | |
use std::collections::*; | |
#[derive(Debug)] | |
pub enum Method { | |
GET, | |
POST, | |
PUT, | |
DELETE, | |
HEAD, | |
OPTIONS, | |
CONNECT, | |
PATCH, | |
TRACE, | |
} | |
impl fmt::Display for Method { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
match self { | |
Method::GET => write!(f, "GET"), | |
Method::POST => write!(f, "POST"), | |
Method::PUT => write!(f, "PUT"), | |
Method::DELETE => write!(f, "DELETE"), | |
Method::HEAD => write!(f, "HEAD"), | |
Method::OPTIONS => write!(f, "OPTIONS"), | |
Method::CONNECT => write!(f, "CONNECT"), | |
Method::PATCH => write!(f, "PATCH"), | |
Method::TRACE => write!(f, "TRACE"), | |
} | |
} | |
} | |
#[derive(Debug)] | |
pub struct Request { | |
method: Method, | |
uri: String, | |
version: String, | |
headers: HashMap<String, String>, | |
body: Option<Vec<u8>>, | |
} | |
impl Request { | |
pub fn new(method: Method, uri: &str) -> Self { | |
Self { | |
method, | |
uri: uri.to_string(), | |
version: "HTTP/1.1".to_string(), | |
headers: HashMap::new(), | |
body: None, | |
} | |
} | |
pub fn header(&mut self, name: &str, value: &str) -> &mut Self { | |
self.headers.insert(name.to_string(), value.to_string()); | |
self | |
} | |
pub fn body(&mut self, body: Vec<u8>) -> &mut Self { | |
self.body = Some(body); | |
self | |
} | |
pub fn send(&self, addr: impl ToSocketAddrs) -> Result<(), Box<dyn std::error::Error>> { | |
let mut stream = TcpStream::connect(addr)?; | |
let mut request = format!( | |
"{} {} {}\r\n", | |
self.method, | |
self.uri, | |
self.version | |
); | |
for (name, value) in &self.headers { | |
request.push_str(&format!("{}: {}\r\n", name, value)); | |
} | |
request.push_str("\r\n"); | |
if let Some(ref body) = self.body { | |
request.push_str(&String::from_utf8_lossy(body)); | |
} | |
// | |
stream.write_all(request.as_bytes())?; | |
stream.flush()?; | |
Ok(()) | |
} | |
} | |
fn main(){ | |
let addrs = [ | |
SocketAddr::from(([127, 0, 0, 1], 8080)), | |
SocketAddr::from(([127, 0, 0, 1], 8081)), | |
]; | |
if let Ok(stream) = TcpStream::connect(&addrs[..]) { | |
println!("Connected to the server!"); | |
} else { | |
println!("Couldn't connect to {:?}", addrs); | |
}; | |
//use Method::GET; | |
//let request = Request::new(GET, "https://mempool.space/api/blocks/tip/height"); | |
//println!("{:?}", request.send("https://mempool.space/api/blocks/tip/height")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment