Implement streaming responses

This commit is contained in:
Valentin Brandl 2019-04-16 21:37:39 +02:00
parent 23c86fac54
commit c6e6a9b5fe
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D

View File

@ -1,13 +1,10 @@
#[macro_use] #[macro_use]
extern crate actix_web; extern crate actix_web;
extern crate badge;
extern crate git2;
extern crate openssl_probe;
extern crate pretty_env_logger;
extern crate structopt;
use actix_web::{http::StatusCode, middleware, web, App, HttpResponse, HttpServer, ResponseError}; use actix_web::{error, middleware, web, App, HttpResponse, HttpServer, ResponseError};
use badge::{Badge, BadgeOptions}; use badge::{Badge, BadgeOptions};
use bytes::Bytes;
use futures::{unsync::mpsc, Stream};
use git2::{Repository, ResetType}; use git2::{Repository, ResetType};
use std::{ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
@ -18,6 +15,8 @@ use structopt::StructOpt;
type State = Arc<String>; type State = Arc<String>;
const INDEX: &str = include_str!("../static/index.html");
#[derive(StructOpt, Debug)] #[derive(StructOpt, Debug)]
struct Opt { struct Opt {
#[structopt( #[structopt(
@ -142,9 +141,11 @@ fn calculate_hoc(
status: hoc.to_string(), status: hoc.to_string(),
}; };
let badge = Badge::new(badge_opt)?; let badge = Badge::new(badge_opt)?;
Ok(HttpResponse::Ok()
.content_type("image/svg+xml") let (tx, rx_body) = mpsc::unbounded();
.body(badge.to_svg())) let _ = tx.unbounded_send(Bytes::from(badge.to_svg().as_bytes()));
Ok(HttpResponse::Ok().streaming(rx_body.map_err(|_| error::ErrorBadRequest("bad request"))))
} }
fn github( fn github(
@ -170,9 +171,10 @@ fn bitbucket(
#[get("/")] #[get("/")]
fn index() -> HttpResponse { fn index() -> HttpResponse {
HttpResponse::build(StatusCode::OK) let (tx, rx_body) = mpsc::unbounded();
.content_type("text/html; charset=utf-8") let _ = tx.unbounded_send(Bytes::from(INDEX.as_bytes()));
.body(include_str!("../static/index.html"))
HttpResponse::Ok().streaming(rx_body.map_err(|_| error::ErrorBadRequest("bad request")))
} }
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {