mirror of
https://github.com/guilhermewerner/mini-redis
synced 2025-06-15 22:45:48 +00:00
Add Get and Set data funcionality
This commit is contained in:
@ -19,15 +19,38 @@ async fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn process(socket: TcpStream) {
|
async fn process(socket: TcpStream) {
|
||||||
// The `Connection` lets us read/write redis **frames** instead of
|
use mini_redis::Command::{self, Get, Set};
|
||||||
// byte streams. The `Connection` type is defined by mini-redis.
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
// A hashmap is used to store data
|
||||||
|
let mut db = HashMap::new();
|
||||||
|
|
||||||
|
// Connection, provided by `mini-redis`, handles parsing frames from
|
||||||
|
// the socket
|
||||||
let mut connection = Connection::new(socket);
|
let mut connection = Connection::new(socket);
|
||||||
|
|
||||||
if let Some(frame) = connection.read_frame().await.unwrap() {
|
// Use `read_frame` to receive a command from the connection.
|
||||||
println!("GOT: {:?}", frame);
|
while let Some(frame) = connection.read_frame().await.unwrap() {
|
||||||
|
let response = match Command::from_frame(frame).unwrap() {
|
||||||
|
Set(cmd) => {
|
||||||
|
// The value is stored as `Vec<u8>`
|
||||||
|
db.insert(cmd.key().to_string(), cmd.value().to_vec());
|
||||||
|
Frame::Simple("OK".to_string())
|
||||||
|
}
|
||||||
|
Get(cmd) => {
|
||||||
|
if let Some(value) = db.get(cmd.key()) {
|
||||||
|
// `Frame::Bulk` expects data to be of type `Bytes`. This
|
||||||
|
// type will be covered later in the tutorial. For now,
|
||||||
|
// `&Vec<u8>` is converted to `Bytes` using `into()`.
|
||||||
|
Frame::Bulk(value.clone().into())
|
||||||
|
} else {
|
||||||
|
Frame::Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cmd => panic!("unimplemented {:?}", cmd),
|
||||||
|
};
|
||||||
|
|
||||||
// Respond with an error
|
// Write the response to the client
|
||||||
let response = Frame::Error("unimplemented".to_string());
|
|
||||||
connection.write_frame(&response).await.unwrap();
|
connection.write_frame(&response).await.unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user