Skip to content

Commit

Permalink
Merge pull request #3 from nsheremet/develop
Browse files Browse the repository at this point in the history
refactor code with rustfmt, add appveyor.yml
  • Loading branch information
Nazarii Sheremet authored Apr 15, 2017
2 parents ee9236c + b92ae1d commit 50add19
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 50 deletions.
41 changes: 41 additions & 0 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
environment:
global:
PROJECT_NAME: knock
matrix:
# Stable channel
- TARGET: i686-pc-windows-gnu
CHANNEL: stable
- TARGET: x86_64-pc-windows-gnu
CHANNEL: stable
# Beta channel
- TARGET: i686-pc-windows-gnu
CHANNEL: beta
- TARGET: x86_64-pc-windows-gnu
CHANNEL: beta
# Nightly channel
- TARGET: i686-pc-windows-gnu
CHANNEL: nightly
- TARGET: x86_64-pc-windows-gnu
CHANNEL: nightly

# Install Rust and Cargo
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
install:
- ps: Start-FileDownload "https://static.rust-lang.org/dist/channel-rust-stable"
- ps: $env:RUST_VERSION = Get-Content channel-rust-stable | select -first 1 | %{$_.split('-')[1]}
- if NOT "%CHANNEL%" == "stable" set RUST_VERSION=%CHANNEL%
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:RUST_VERSION}-${env:TARGET}.exe"
- rust-%RUST_VERSION%-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust"
- SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin
- if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin
- if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin
- rustc -V
- cargo -V

# ???
build: false

# Build rustfmt, run the executables as
test_script:
- cargo build --verbose
- cargo test
4 changes: 3 additions & 1 deletion src/consts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
pub const HTTP_VERSION: &'static str = "HTTP/1.1";
pub const CL_METHODS: [&'static str; 2] = ["POST", "PUT"];
pub const C_TYPE: [&'static str; 3] = ["application/json", "application/x-www-form-urlencoded", "multipart/form-data"];
pub const C_TYPE: [&'static str; 3] = ["application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"];
pub const SEP: &'static str = "\r\n";

pub const DEF_PORT: u16 = 80;
Expand Down
113 changes: 66 additions & 47 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,29 @@ impl HTTP {
// Response: Result<HTTP, HttpError>
//
pub fn new(url: &str) -> Result<HTTP, HttpError> {
let response = Response { status: 0, header: HashMap::new(), body: String::new() };
let response = Response {
status: 0,
header: HashMap::new(),
body: String::new(),
};
let url = try!(Url::parse(url));
let host_url = match url.host_str() {
Some(url) => url.to_string(),
None => String::new()
None => String::new(),
};

Ok(HTTP {
response: response,
url: url,
response: response,
url: url,

method: String::new(),
body: HashMap::new(),
header: HashMap::new(),
method: String::new(),
body: HashMap::new(),
header: HashMap::new(),

host: host_url,
boundary: String::new(),
response_str: String::new(),
})
host: host_url,
boundary: String::new(),
response_str: String::new(),
})
}

///
Expand Down Expand Up @@ -174,26 +178,26 @@ impl HTTP {
let mut response = String::new();

if self.url.scheme() == "http" {
let port = match self.url.port() {
Some(p) => p,
None => DEF_PORT,
};
let addr = format!("{}:{}", url, port);
let mut stream = try!(TcpStream::connect(addr));
try!(stream.write(request.as_bytes()));
try!(stream.read_to_string(&mut self.response_str));
let port = match self.url.port() {
Some(p) => p,
None => DEF_PORT,
};
let addr = format!("{}:{}", url, port);
let mut stream = try!(TcpStream::connect(addr));
try!(stream.write(request.as_bytes()));
try!(stream.read_to_string(&mut self.response_str));
} else {
let port = match self.url.port() {
Some(p) => p,
None => DEF_SSL_PORT,
};
let addr = format!("{}:{}", url, port);
let connector = try!(SslConnectorBuilder::new(SslMethod::tls())).build();
let stream = try!(TcpStream::connect(addr));
let mut stream = try!(connector.connect(&self.host, stream));

try!(stream.write(request.as_bytes()));
try!(stream.read_to_string(&mut response));
let port = match self.url.port() {
Some(p) => p,
None => DEF_SSL_PORT,
};
let addr = format!("{}:{}", url, port);
let connector = try!(SslConnectorBuilder::new(SslMethod::tls())).build();
let stream = try!(TcpStream::connect(addr));
let mut stream = try!(connector.connect(&self.host, stream));

try!(stream.write(request.as_bytes()));
try!(stream.read_to_string(&mut response));
}

let resp = Response::new(response).unwrap();
Expand All @@ -218,13 +222,17 @@ impl HTTP {
match method_exist {
Some(_) => {
header.insert(H_CLEN.to_string(), body.len().to_string());
},
None => { },
}
None => {}
}
}

let mut str = String::new();
str += &format!("{} {} {}{}", self.method, self.url.path(), HTTP_VERSION, SEP);
str += &format!("{} {} {}{}",
self.method,
self.url.path(),
HTTP_VERSION,
SEP);

for (key, val) in &header {
str += &format!("{}: {}{}", key, val, SEP);
Expand All @@ -241,8 +249,11 @@ impl HTTP {
//
// Response: Result<String, HttpError>
//
fn create_body(c_type: &str, body: &HashMap<String, Data>, mut header: HashMap<String, String>, b: &str)
-> Result<String, HttpError> {
fn create_body(c_type: &str,
body: &HashMap<String, Data>,
mut header: HashMap<String, String>,
b: &str)
-> Result<String, HttpError> {
let mut res = String::new();

if c_type == C_TYPE[1] {
Expand All @@ -264,14 +275,15 @@ fn create_body(c_type: &str, body: &HashMap<String, Data>, mut header: HashMap<S
&Data::File(ref str) => {
res += &format!("Content-Disposition: form-data; name={};", key);
let file_name = try!(Path::new(str)
.file_name()
.ok_or(Error::new(ErrorKind::InvalidData, "wrong file path")));
.file_name()
.ok_or(Error::new(ErrorKind::InvalidData,
"wrong file path")));
res += &format!(" filename={0}{1}{1}", file_name.to_str().unwrap(), SEP);
let mut buffer = String::new();
let mut file = try!(File::open(str));
try!(file.read_to_string(&mut buffer));
res += &format!("{}{}", buffer, SEP);
},
}
&Data::String(ref str) => {
res += &format!("Content-Disposition: form-data; name={0}{1}{1}", key, SEP);
res += &format!("{}{}", str, SEP);
Expand All @@ -286,7 +298,7 @@ fn create_body(c_type: &str, body: &HashMap<String, Data>, mut header: HashMap<S
match val {
&Data::String(ref str) => {
tmp_map.insert(key, str);
},
}
&Data::File(_) => continue,
}
}
Expand All @@ -304,15 +316,16 @@ fn create_body(c_type: &str, body: &HashMap<String, Data>, mut header: HashMap<S
//
// Response: (Result<String, HttpError>, String)
//
fn organize_header(header: &HashMap<String, String>, host: String)
-> (HashMap<String, String>, String) {
fn organize_header(header: &HashMap<String, String>,
host: String)
-> (HashMap<String, String>, String) {
let mut data: HashMap<String, String> = HashMap::new();
let mut c_type = String::new();

if !header.is_empty() {
for (key, val) in header {
if data.contains_key(val) {
let p_val = data.get(key).unwrap().to_string(); // Always be Some(val)
let p_val = data.get(key).unwrap().to_string(); // Always be Some(val)
let str = format!("{}; {}", p_val, val);
data.insert(key.to_string(), str);
} else {
Expand All @@ -321,18 +334,24 @@ fn organize_header(header: &HashMap<String, String>, host: String)
}
}

if !data.contains_key(H_HOST) { data.insert(H_HOST.to_string(), host.to_string()); }
if !data.contains_key(H_ACCPT) { data.insert(H_ACCPT.to_string(), DEF_ACCEPT.to_string()); }
if !data.contains_key(H_CONN) { data.insert(H_CONN.to_string(), DEF_CONN.to_string()); }
if !data.contains_key(H_HOST) {
data.insert(H_HOST.to_string(), host.to_string());
}
if !data.contains_key(H_ACCPT) {
data.insert(H_ACCPT.to_string(), DEF_ACCEPT.to_string());
}
if !data.contains_key(H_CONN) {
data.insert(H_CONN.to_string(), DEF_CONN.to_string());
}
if data.contains_key(H_CTYPE) {
let c_types = C_TYPE.clone();
c_type = data.get(H_CTYPE).unwrap().to_string();
let c_type_exist = c_types.iter().find(|&&x| x == c_type);
match c_type_exist {
None => {
data.insert(H_CTYPE.to_string(), C_TYPE[0].to_string());
},
Some(_) => { },
}
Some(_) => {}
}
} else {
data.insert(H_CTYPE.to_string(), C_TYPE[0].to_string());
Expand Down
10 changes: 8 additions & 2 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,20 @@ impl Response {
let v = tmp_vec[1];
if header.contains_key(k) {
let value;
{ value = header.get(k).unwrap().to_string(); }
{
value = header.get(k).unwrap().to_string();
}
header.insert(k.to_string(), format!("{}; {}", value, v));
} else {
header.insert(k.to_string(), v.to_string());
}
}
}

Ok(Response { status: status, header: header, body: body })
Ok(Response {
status: status,
header: header,
body: body,
})
}
}

0 comments on commit 50add19

Please sign in to comment.