initial commit

This commit is contained in:
Helba 2024-01-26 12:01:43 -08:00
commit 9609c7ab83
7 changed files with 3151 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
.idea
.vscode

3019
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

30
Cargo.toml Normal file
View file

@ -0,0 +1,30 @@
[package]
name = "microservice"
version = "0.1.0"
edition = "2021"
build = "build.rs"
[dependencies]
tokio = { version = "1.20.0", features = ["rt", "macros"] }
sea-orm = { version = "0.12.12", features = [
"sqlx-postgres",
"runtime-tokio-native-tls",
"with-json",
] }
serde = { version = "1.0.130", features = ["derive"] }
actix-web = "4"
env_logger = "0.11.0"
[target.'cfg(unix)'.dependencies]
openssl = { version = "0.10.63", features = ["vendored"] }
[build-dependencies]
vcpkg = "0.2.15"
[profile.release]
strip = true
opt-level = 's'
lto = true
debug = 0
codegen-units = 1
panic = 'abort'

13
Dockerfile Normal file
View file

@ -0,0 +1,13 @@
FROM rust:slim as builder
RUN apt-get update && apt-get install -y libpq-dev libssl-dev pkg-config musl-tools perl make && rm -rf /var/lib/apt/lists/*
RUN rustup target add x86_64-unknown-linux-musl
WORKDIR /app
COPY . /app
RUN cargo build --release --target x86_64-unknown-linux-musl
RUN strip /app/target/x86_64-unknown-linux-musl/release/microservice
FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/microservice /microservice
WORKDIR /
CMD ["/microservice"]

19
README.MD Normal file
View file

@ -0,0 +1,19 @@
## A simple rust project for microservices using rust, actix, and postgres
This project contains a simple rust project for microservices using rust, actix, and postgres.
The `Dockerfile` in this project is used to build a docker image for the rust project, the output Docker image is a from scratch image that contains the rust binary.
### Building and running the docker image
To build the docker image, run the following command:
```bash
> docker build -t f:latest .
```
To run the docker image, run the following command:
```bash
docker run -i -e RUST_LOG="debug" -e DATABASE_URL="postgresql://postgres:postgres@host.docker.internal:5432/database" -e LISTEN="0.0.0.0:8080" -p 8080:8080 f:latest
```

11
build.rs Normal file
View file

@ -0,0 +1,11 @@
#[cfg(target_os = "windows")]
fn main() {
vcpkg::Config::new()
.emit_includes(true)
.copy_dlls(true)
.find_package("libpq").unwrap();
}
#[cfg(not(target_os = "windows"))]
fn main() {
}

56
src/main.rs Normal file
View file

@ -0,0 +1,56 @@
use actix_web::{get, middleware, web, App, Error, HttpResponse, HttpServer};
use sea_orm::{Database, DatabaseConnection};
use serde::{Deserialize, Serialize};
use std::env;
use std::time::Duration;
mod enities;
#[derive(Debug, Clone)]
struct State {
db: DatabaseConnection,
}
#[derive(Debug, Serialize, Deserialize)]
struct Response {
health: bool,
}
#[get("/")]
async fn index(_: web::Data<State>) -> actix_web::Result<HttpResponse, Error> {
Ok(HttpResponse::Ok().json(Response { health: true }))
}
#[actix_web::main]
async fn main() -> actix_web::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let server_url = env::var("LISTEN").unwrap_or("127.0.0.1:8080".to_string());
let mut opts =
sea_orm::ConnectOptions::new(env::var("DATABASE_URL").expect("DATABASE_URL ust be set"));
opts.max_connections(5)
.min_connections(1)
.connect_timeout(Duration::from_secs(8))
.acquire_timeout(Duration::from_secs(8))
.idle_timeout(Duration::from_secs(8))
.max_lifetime(Duration::from_secs(8));
let db: DatabaseConnection = Database::connect(opts)
.await
.expect("Failed to connect to database");
let state = State { db };
let _ = HttpServer::new(move || {
App::new()
.app_data(web::Data::new(state.clone()))
.wrap(middleware::Logger::default()) // enable logger
.service(index)
})
.bind(&server_url)?
.run()
.await?;
Ok(())
}