Skip to content

Instantly share code, notes, and snippets.

@ifukazoo
Created February 10, 2020 00:38
Show Gist options
  • Save ifukazoo/a721e4ce502d1526b744b1373f97007f to your computer and use it in GitHub Desktop.
Save ifukazoo/a721e4ce502d1526b744b1373f97007f to your computer and use it in GitHub Desktop.
[package]
name = "webexample"
version = "0.1.0"
authors = ["ifukazoo <ifukazoo@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tower-web = "*"
reqwest = { version = "0.10", features = ["blocking", "json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "*"
#[macro_use]
extern crate tower_web;
extern crate reqwest;
extern crate serde;
use reqwest::blocking;
use serde::{Deserialize, Serialize};
use tower_web::ServiceBuilder;
/// This type will be part of the web service as a resource.
#[derive(Clone, Debug)]
struct HelloWorld;
/// This will be the JSON response
#[derive(Response)]
struct HelloResponse {
message: &'static str,
}
#[derive(Response)]
struct UserResponse {
users: Vec<User>,
}
#[derive(Serialize, Deserialize, Clone)]
struct User {
userId: i32,
id: i32,
title: String,
body: String,
}
impl_web! {
impl HelloWorld {
#[get("/")]
#[content_type("json")]
fn hello_world(&self) -> Result<HelloResponse, ()> {
Ok(HelloResponse {
message: "hello world",
})
}
#[get("/user")]
#[content_type("json")]
fn get_user(&self) -> Result<UserResponse, ()> {
let resp = reqwest::blocking::get("https://jsonplaceholder.typicode.com/posts?userId=1").unwrap();
let json = resp.json::<Vec<User>>().unwrap();
let mut json = json.clone();
for u in &mut json {
u.id = 0xFF;
}
let serialized = serde_json::to_string(&json).unwrap();
Ok(UserResponse {
users: json,
})
}
}
}
pub fn main() {
let addr = "127.0.0.1:8082".parse().expect("Invalid address");
println!("Listening on http://{}", addr);
ServiceBuilder::new()
.resource(HelloWorld)
.run(&addr)
.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment