conf. en variables de entorno

This commit is contained in:
serxoz 2022-10-24 10:23:47 +02:00
parent d738418a91
commit c2167c2126
5 changed files with 33 additions and 8 deletions

View File

@ -4,6 +4,14 @@ Servicio para compartir arquivos.
Recibe un arquivo. Recibe un arquivo.
Devolve un link para descargalo. Devolve un link para descargalo.
## Execución
```
UPLOADS="/tmp/uploads/" PORT=4000 cargo run
```
As variables de entorno UPLOADS e PORT son opcionais tendo como valores por defecto:
- UPLOADS = "uploads/"
- PORT = 3000
## Funcionamento ## Funcionamento
``` ```
curl -F'file=@fondo-mobil.jpg' https://sh4r.in curl -F'file=@fondo-mobil.jpg' https://sh4r.in

View File

@ -1,4 +1,5 @@
use rand::{distributions::Alphanumeric, Rng}; // 0.8 use rand::{distributions::Alphanumeric, Rng}; // 0.8
use std::env;
pub fn randstr() -> String { pub fn randstr() -> String {
rand::thread_rng() rand::thread_rng()
@ -7,3 +8,21 @@ pub fn randstr() -> String {
.map(char::from) .map(char::from)
.collect() .collect()
} }
// le a variable de entorno UPLOADS para configurar o directorio de almacenamento
// por defecto: dir_actual/uploads/
pub fn env_uploads_dir() -> String {
match env::var_os("UPLOADS") {
Some(val) => val.into_string().unwrap(),
None => "uploads/".to_string(),
}
}
// le a variable de entorno PORT para configurar o porto de escoita
// por defecto o 3000
pub fn env_listen_port() -> u16 {
match env::var_os("PORT") {
Some(val) => val.into_string().unwrap().parse::<u16>().unwrap(),
None => 3000,
}
}

View File

@ -6,6 +6,7 @@ use axum::{
Router, Router,
}; };
use std::net::SocketAddr; use std::net::SocketAddr;
use crate::lib::env_listen_port;
use crate::vistas::{download::get_file, root::basic, upload::upload}; use crate::vistas::{download::get_file, root::basic, upload::upload};
@ -22,7 +23,7 @@ async fn main() {
// run our app with hyper // run our app with hyper
// `axum::Server` is a re-export of `hyper::Server` // `axum::Server` is a re-export of `hyper::Server`
let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let addr = SocketAddr::from(([127, 0, 0, 1], env_listen_port()));
tracing::debug!("listening on {}", addr); tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr) axum::Server::bind(&addr)
.serve(app.into_make_service()) .serve(app.into_make_service())

View File

@ -5,8 +5,7 @@ use axum::{
}; };
use tokio::fs::read_dir; use tokio::fs::read_dir;
use tokio_util::io::ReaderStream; use tokio_util::io::ReaderStream;
use crate::lib::env_uploads_dir;
const BASE_PATH: &str = "uploads";
pub async fn get_file(axum::extract::Path(hash): axum::extract::Path<String>) -> impl IntoResponse { pub async fn get_file(axum::extract::Path(hash): axum::extract::Path<String>) -> impl IntoResponse {
// find file from hash // find file from hash
@ -41,7 +40,7 @@ async fn find_file(hash: String) -> Result<(String, String), tokio::io::Error> {
let mut file_path = String::from(""); let mut file_path = String::from("");
let mut file_name = String::from(""); let mut file_name = String::from("");
let pai = &hash[0..1]; //primeiro char let pai = &hash[0..1]; //primeiro char
let path = format!("{}/{}/{}", BASE_PATH, pai, hash); let path = format!("{}/{}/{}", env_uploads_dir(), pai, hash);
let mut dir = read_dir(path).await?; let mut dir = read_dir(path).await?;
while let Some(child) = dir.next_entry().await? { while let Some(child) = dir.next_entry().await? {

View File

@ -1,12 +1,10 @@
use crate::lib::randstr; use crate::lib::{randstr, env_uploads_dir};
use axum::{ use axum::{
extract::Multipart, extract::Multipart,
response::{IntoResponse, Response}, response::{IntoResponse, Response},
}; };
use tokio::{fs::create_dir_all, fs::File, io::AsyncWriteExt}; use tokio::{fs::create_dir_all, fs::File, io::AsyncWriteExt};
const BASE_PATH: &str = "uploads";
// upload view // upload view
pub async fn upload(mut multipart: Multipart) -> Response { pub async fn upload(mut multipart: Multipart) -> Response {
let mut link = String::from(""); let mut link = String::from("");
@ -21,7 +19,7 @@ pub async fn upload(mut multipart: Multipart) -> Response {
let fillo = randstr(); // directorio que aloxará o arquivo let fillo = randstr(); // directorio que aloxará o arquivo
let pai = &fillo[0..1]; // agrupase por directorios co mesmo comezo (1ºchar) let pai = &fillo[0..1]; // agrupase por directorios co mesmo comezo (1ºchar)
let path = format!("{}/{}/{}", BASE_PATH, pai, fillo); let path = format!("{}/{}/{}", env_uploads_dir(), pai, fillo);
let dest = format!("{}/{}", path, filename); let dest = format!("{}/{}", path, filename);
create_dir_all(&path) create_dir_all(&path)