Skip to content

Instantly share code, notes, and snippets.

@benaryorg
Last active August 29, 2015 14:21
Show Gist options
  • Save benaryorg/1e3c8576a94b09722238 to your computer and use it in GitHub Desktop.
Save benaryorg/1e3c8576a94b09722238 to your computer and use it in GitHub Desktop.
get text from an HTTP server in rust with cli options
use std::env;
use std::net::*;
use std::io::prelude::*;
use getopts::Options;
extern crate getopts;
fn main()
{
let mut opts = Options::new();
opts.optflag("h","help","display this help and exit");
opts.optopt("p","port","use specific port","PORT");
let args:Vec<String>=env::args().collect();
let program=args[0].clone();
let matches=opts.parse(&args[1..]).unwrap();
if matches.opt_present("h")
{
println!("{}",opts.usage(&format!("{} SERVER[/PATH]\n\nReturns the result of \
an HTTP request to the server SERVER with an optional\npath of PATH.",
opts.short_usage(&program))));
return;
}
let port:u16=match matches.opt_str("p")
{
Some(x)=>x.parse::<u16>().unwrap(),
_=>80,
};
let ip=if matches.free.len()!=1
{
println!("{} SERVER[/PATH]\n\nReturns the result of an HTTP request to\
the server SERVER with an optional\npath of PATH.",
opts.short_usage(&program));
return;
}
else
{
matches.free[0].split("/").next().unwrap()
};
let path:String=matches.free[0].split("/").skip(1).collect();
let mut buf:Box<String>;
let mut stream=TcpStream::connect((ip,port)).unwrap();
let _=stream.write(&format!("GET /{} HTTP/1.0\nHost: {}\n",path,ip).into_bytes());
while
{
buf=Box::new(String::new());
let res=stream.read_to_string(&mut *buf).unwrap();
print!("{}",*buf);
res>0
}{}
println!("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment