e4d6ac74d36e42e87ebc0658b40dcbe0b55ba141
4 use actix_web
::{get
, web
, App
, HttpServer
, HttpResponse
, Responder
, ResponseError
, Result
};
5 use actix_web
::body
::BoxBody
;
6 use actix_web
::http
::StatusCode
;
7 use image
::{ImageBuffer
, ColorType
, RgbImage
, write_buffer_with_format
};
8 use image
::ImageOutputFormat
::Png
;
11 struct ImageError(image
::ImageError
);
13 impl Display
for ImageError
{
14 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
15 write
!(f
, "{}", &self.0)
19 impl ResponseError
for ImageError
{
20 fn status_code(&self) -> StatusCode
{
21 StatusCode
::INTERNAL_SERVER_ERROR
24 fn error_response(&self) -> HttpResponse
<BoxBody
> {
25 HttpResponse
::InternalServerError().fin
ish
()
29 fn to_imageresult
<T
> (result
: Result
<T
, image
::ImageError
>) -> Result
<T
, ImageError
> {
32 Err(e
) => Err(ImageError(e
))
36 #[get("/hello/{name}")]
37 async
fn greet(name
: web
::Path
<String
>) -> impl Responder
{
38 format
!("Hello {name}!")
42 async
fn img_gen(data
: web
::Path
<String
>) -> Result
<impl Responder
> {
43 let mut cursor
= Cursor
::new(Vec
::new());
44 let img
: RgbImage
= ImageBuffer
::new(512, 512);
45 to_imageresult(write_buffer_with_format(&mut cursor
, &img
, 512, 512, ColorType
::Rgb8
, Png
))?
;
46 Ok(cursor
.into
_inner
().customize().insert
_header
(("content-type", "image/png")))
49 #[actix_web::main] // or #[tokio::main]
50 async
fn main() -> std
::io
::Result
<()> {
52 App
::new().service(greet
).service(img_gen
)
54 .bind(("127.0.0.1", 8080))?