summaryrefslogtreecommitdiff
path: root/src/types/response.rs
diff options
context:
space:
mode:
authorTyler Murphy <tylermurphy534@gmail.com>2023-01-26 17:29:16 -0500
committerTyler Murphy <tylermurphy534@gmail.com>2023-01-26 17:29:16 -0500
commit88209d88236c3d865a9f5174a0dced31920859bf (patch)
tree89a9985927393005cf632950b585a6a227b1c679 /src/types/response.rs
downloadxssbook-88209d88236c3d865a9f5174a0dced31920859bf.tar.gz
xssbook-88209d88236c3d865a9f5174a0dced31920859bf.tar.bz2
xssbook-88209d88236c3d865a9f5174a0dced31920859bf.zip
i did things
Diffstat (limited to 'src/types/response.rs')
-rw-r--r--src/types/response.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/types/response.rs b/src/types/response.rs
new file mode 100644
index 0000000..bea3406
--- /dev/null
+++ b/src/types/response.rs
@@ -0,0 +1,60 @@
+use axum::{response::{IntoResponse, Response}, http::{StatusCode, Request, HeaderValue}, body::Body, headers::HeaderName};
+use tower::ServiceExt;
+use tower_http::services::ServeFile;
+
+#[derive(Debug)]
+pub enum ResponseCode {
+ Success,
+ Created,
+ BadRequest,
+ Unauthorized,
+ Forbidden,
+ NotFound,
+ ImATeapot,
+ InternalServerError
+}
+
+impl ResponseCode {
+ pub fn code(self) -> StatusCode {
+ match self {
+ Self::Success => StatusCode::OK,
+ Self::Created => StatusCode::CREATED,
+ Self::BadRequest => StatusCode::BAD_REQUEST,
+ Self::Unauthorized => StatusCode::UNAUTHORIZED,
+ Self::Forbidden => StatusCode::FORBIDDEN,
+ Self::NotFound => StatusCode::NOT_FOUND,
+ Self::ImATeapot => StatusCode::IM_A_TEAPOT,
+ Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR
+ }
+ }
+
+ pub fn msg(self, msg: &str) -> Response {
+ (self.code(), msg.to_owned()).into_response()
+ }
+
+ pub fn json(self, json: &str) -> Response {
+ let mut res = (self.code(), json.to_owned()).into_response();
+ res.headers_mut().insert(
+ HeaderName::from_static("content-type"), HeaderValue::from_static("application/json"),
+ );
+ res
+ }
+
+ pub async fn file(self, path: &str) -> Result<Response> {
+ if path.chars().position(|c| c == '.' ).is_none() {
+ return Err(ResponseCode::BadRequest.msg("Folders cannot be served"));
+ }
+ let path = format!("public{}", path);
+ let svc = ServeFile::new(path);
+ let Ok(mut res) = svc.oneshot(Request::new(Body::empty())).await else {
+ return Err(ResponseCode::InternalServerError.msg("Error wile fetching file"));
+ };
+ if res.status() != StatusCode::OK {
+ return Err(ResponseCode::NotFound.msg("File not found"));
+ }
+ *res.status_mut() = self.code();
+ Ok(res.into_response())
+ }
+}
+
+pub type Result<T> = std::result::Result<T, Response>; \ No newline at end of file