i added db and articles end points

This commit is contained in:
linlkin 2024-12-05 23:19:15 +01:00
parent c992014d53
commit 57d574d143
4 changed files with 43 additions and 3 deletions

View file

@ -1,10 +1,14 @@
use actix_web::{App, HttpServer};
use actix_web::{get, http, post, web, App, HttpResponse, HttpServer, Responder};
use actix_files::Files;
use sqlite::{Connection, State, Error};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
async fn main() -> Result<(), std::io::Error> {
let conn = Connection::open("./data/data.db");
HttpServer::new(|| {
App::new()
.service(hello)
.service(Files::new("/", "./public").index_file("index.html"))
})
.bind(("0.0.0.0", 8080))?
@ -12,3 +16,24 @@ async fn main() -> std::io::Result<()> {
.await
}
#[get("/api/hello")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[get("/api/articles")]
async fn get_articles() -> impl Responder {
let conn = Connection::open("./data/data.db").unwrap();
let mut stmt = conn.prepare("SELECT * FROM articles").unwrap();
let mut articles = Vec::new();
while let State::Row = stmt.next().unwrap() {
let id = stmt.read::<i64, _>(0).unwrap();
let title = stmt.read::<String, _>(1).unwrap();
let subTitle = stmt.read::<String, _>(2).unwrap();
let content = stmt.read::<String, _>(3).unwrap();
articles.push((id, title, subTitle, content));
}
HttpResponse::Ok().json(articles)
}