Skip to content

Commit

Permalink
Add a custom response builder (snapview#158)
Browse files Browse the repository at this point in the history
* add custom reponse builder

* change names and shorten implemtation

* Re-format the code

Co-authored-by: Daniel Abramov <dabramov@snapview.de>
  • Loading branch information
Austaras and daniel-abramov committed Dec 30, 2020
1 parent b0a6bae commit 4d70f63
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
6 changes: 2 additions & 4 deletions src/client.rs
Expand Up @@ -119,10 +119,8 @@ pub fn connect_with_config<Req: IntoClientRequest>(
}

fn create_request(parts: &Parts, uri: &Uri) -> Request {
let mut builder = Request::builder()
.uri(uri.clone())
.method(parts.method.clone())
.version(parts.version);
let mut builder =
Request::builder().uri(uri.clone()).method(parts.method.clone()).version(parts.version);
*builder.headers_mut().expect("Failed to create `Request`") = parts.headers.clone();
builder.body(()).expect("Failed to create `Request`")
}
Expand Down
22 changes: 18 additions & 4 deletions src/handshake/server.rs
Expand Up @@ -6,7 +6,9 @@ use std::{
result::Result as StdResult,
};

use http::{HeaderMap, Request as HttpRequest, Response as HttpResponse, StatusCode};
use http::{
response::Builder, HeaderMap, Request as HttpRequest, Response as HttpResponse, StatusCode,
};
use httparse::Status;
use log::*;

Expand All @@ -30,8 +32,7 @@ pub type Response = HttpResponse<()>;
/// Server error response type.
pub type ErrorResponse = HttpResponse<Option<String>>;

/// Create a response for the request.
pub fn create_response(request: &Request) -> Result<Response> {
fn create_parts<T>(request: &HttpRequest<T>) -> Result<Builder> {
if request.method() != http::Method::GET {
return Err(Error::Protocol("Method is not GET".into()));
}
Expand Down Expand Up @@ -76,7 +77,20 @@ pub fn create_response(request: &Request) -> Result<Response> {
.header("Upgrade", "websocket")
.header("Sec-WebSocket-Accept", convert_key(key.as_bytes())?);

Ok(builder.body(())?)
Ok(builder)
}

/// Create a response for the request.
pub fn create_response(request: &Request) -> Result<Response> {
Ok(create_parts(&request)?.body(())?)
}

/// Create a response for the request with a custom body.
pub fn create_response_with_body<T>(
request: &HttpRequest<T>,
generate_body: impl FnOnce() -> T,
) -> Result<HttpResponse<T>> {
Ok(create_parts(&request)?.body(generate_body())?)
}

// Assumes that this is a valid response
Expand Down

0 comments on commit 4d70f63

Please sign in to comment.