使用 Diesel 和 Rocket,我希望能够记录请求来自的 IP。这是类似的讨论,但没有结论。Diesel 将 Postgresinet
类型映射到IpNetwork
,但 RocketSocketAddr
从请求数据中返回。如何转换SocketAddr
为IpNetwork
?
模型.rs:
#![allow(proc_macro_derive_resolution_fallback)]
use crate::schema::bs_date_forecast;
use chrono::{NaiveDate, NaiveDateTime};
use ipnetwork::IpNetwork;
use diesel::prelude::*;
#[derive(Queryable, Insertable, Serialize, Deserialize)]
#[table_name="bs_date_forecast"]
pub struct BsDateForecast {
pub id: Option<i32>,
pub predicted_date: NaiveDate,
pub seer_ip: IpNetwork,
pub created_timestamp: NaiveDateTime, // Defined automatically at the database level
}
impl BsDateForecast {
pub fn create(forecast: BsDateForecast,
conn: &PgConnection) -> Vec<BsDateForecast> {
diesel::insert_into(bs_date_forecast::table)
.values(&forecast)
.get_results(conn)
.expect("Error creating record")
}
}
路线.rs:
#[post("/predictions", format = "application/json", data = "<prediction>")]
pub fn create(prediction: Json<BsDateForecast>,
conn: DbConn,
user_ip: SocketAddr) -> Json<Vec<BsDateForecast>> {
let insert = BsDateForecast{
id: None,
seer_ip: user_ip.to_string(), // How to get IpNetwork here???
..prediction.into_inner()
};
Json(BsDateForecast::create(insert, &conn))
}