Skip to content

Commit

Permalink
fix: return 400 error for missing resource in web server GET request
Browse files Browse the repository at this point in the history
  • Loading branch information
jopemachine committed Oct 1, 2024
1 parent a4ba780 commit 015cad4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
17 changes: 11 additions & 6 deletions binding/python/examples/web_server_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,23 @@ async def __aexit__(self, exc_type, exc, tb):
"""


@routes.get("/store/{id}")
@routes.get("/store/{key}")
async def get(request: web.Request) -> web.Response:
store: HashStore = request.app["state"]["store"]
id = request.match_info["id"]
return web.Response(text=store.get(id))
key = request.match_info["key"]
value = store.get(key)

if value is None:
return web.Response(status=400, text="Bad Request: Item not found")

@routes.put("/store/{id}/{value}")
return web.Response(text=value)


@routes.put("/store/{key}/{value}")
async def put(request: web.Request) -> web.Response:
raft: Raft = request.app["state"]["raft"]
id, value = request.match_info["id"], request.match_info["value"]
message = SetCommand(id, value)
key, value = request.match_info["key"], request.match_info["value"]
message = SetCommand(key, value)

raft_node = raft.get_raft_node()
await raft_node.propose(message.encode())
Expand Down
14 changes: 8 additions & 6 deletions examples/memstore/src/web_server_api.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::collections::HashMap;

use actix_web::{get, put, web, Responder};
use actix_web::{get, put, web, HttpResponse, Responder};
use raftify::{raft::Storage, AbstractLogEntry, StableStorage};
use serde_json::Value;

use crate::state_machine::{HashStore, LogEntry, Raft};

#[put("/store/{id}/{value}")]
#[put("/store/{key}/{value}")]
async fn put(data: web::Data<(HashStore, Raft)>, path: web::Path<(u64, String)>) -> impl Responder {
let log_entry = LogEntry::Insert {
key: path.0,
Expand All @@ -17,12 +17,14 @@ async fn put(data: web::Data<(HashStore, Raft)>, path: web::Path<(u64, String)>)
"OK".to_string()
}

#[get("/store/{id}")]
#[get("/store/{key}")]
async fn get(data: web::Data<(HashStore, Raft)>, path: web::Path<u64>) -> impl Responder {
let id = path.into_inner();
let key = path.into_inner();

let response = data.0.get(id);
format!("{:?}", response)
match data.0.get(key) {
Some(value) => HttpResponse::Ok().body(value),
None => HttpResponse::BadRequest().body("Bad Request: Item not found"),
}
}

#[get("/leader")]
Expand Down

0 comments on commit 015cad4

Please sign in to comment.