Skip to content

Instantly share code, notes, and snippets.

View carlosm27's full-sized avatar
🐺

Carlos Armando Marcano Vargas carlosm27

🐺
View GitHub Profile
@carlosm27
carlosm27 / main.rs
Created April 18, 2023 23:58
Tunnel function
async fn tunnel(mut upgraded: Upgraded, addr: String) -> std::io::Result<()> {
let mut server = TcpStream::connect(addr).await?;
let (from_client, from_server) =
tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?;
tracing::debug!(
"client wrote {} bytes and received {} bytes",
from_client,
from_server
@carlosm27
carlosm27 / main.rs
Created April 18, 2023 23:57
Proxy function
async fn proxy(req: Request<Body>) -> Result<Response, hyper::Error> {
tracing::trace!(?req);
if let Some(host_addr) = req.uri().authority().map(|auth| auth.to_string()) {
if check_address_block(&host_addr) == true {
println!("This site is blocked")
} else {
tokio::task::spawn(async move {
match hyper::upgrade::on(req).await {
Ok(upgraded) => {
@carlosm27
carlosm27 / helpers.rs
Created April 18, 2023 23:56
Check address function
pub fn check_address_block(address_to_check: &str) -> bool {
let addresses_blocked = read_file_lines_to_vec(&"./blacklist.txt".to_string());
let addresses_blocked_iter: Vec<String> = match addresses_blocked {
Ok(vector) => vector,
Err(_) => vec!["Error".to_string()]
};
let address_in = addresses_blocked_iter.contains(&address_to_check.to_string());
return address_in
@carlosm27
carlosm27 / helpers.rs
Created April 18, 2023 23:55
Read file function
use std::fs;
use std::io::BufReader;
use std::io::BufRead;
use std::io;
pub fn read_file_lines_to_vec(filename: &str) -> io::Result<Vec<String>> {
let file_in = fs::File::open(filename)?;
let file_reader = BufReader::new(file_in);
Ok(file_reader.lines().filter_map(io::Result::ok).collect())
}
@carlosm27
carlosm27 / main.rs
Created April 18, 2023 23:53
Adding trace layer
...
use tower_http::trace::{self, TraceLayer};
use tracing::Level;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
.init();
@carlosm27
carlosm27 / main.rs
Created April 18, 2023 23:50
Axum http-proxy example
use axum::{
body::{self, Body},
http::{Method, Request, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
};
use hyper::upgrade::Upgraded;
use std::net::SocketAddr;
use tokio::net::TcpStream;
@carlosm27
carlosm27 / main.go
Created April 10, 2023 17:58
Complete main.go file with prometheus handler
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
@carlosm27
carlosm27 / main.rs
Created March 31, 2023 15:55
track_metrics function
async fn track_metrics<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
let start = Instant::now();
let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
matched_path.as_str().to_owned()
} else {
req.uri().path().to_owned()
};
let method = req.method().clone();
let response = next.run(req).await;
@carlosm27
carlosm27 / main.rs
Created March 31, 2023 15:53
Metrics recorder
fn setup_metrics_recorder() -> PrometheusHandle {
const EXPONENTIAL_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
PrometheusBuilder::new()
.set_buckets_for_metric(
Matcher::Full("http_requests_duration_seconds".to_string()),
EXPONENTIAL_SECONDS,
)
@carlosm27
carlosm27 / main.rs
Created March 31, 2023 15:52
Metrics server starter
async fn start_metrics_server() {
let app = metrics_app();
// NOTE: expose metrics endpoint on a different port
let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap()