Skip to content
Snippets Groups Projects
Unverified Commit f7d1aad6 authored by Louis's avatar Louis :fire:
Browse files

Support custom headers for responses

parent f948e33b
No related branches found
No related tags found
1 merge request!2Scripting
......@@ -36,6 +36,6 @@ impl <'form> FromForm<'form> for ScriptParams {
#[get("/__run_script__?<params>")]
pub fn route_script(params: ScriptParams, runtime: LuaRuntime) -> ScriptResponse {
let lua: Lua = runtime.into(); //todo: Use This
run_script(format!("example/.swerve/{}", params.script_name), &lua).unwrap_or_else(|| ScriptResponse::default())
let lua: Lua = runtime.into();
run_script(format!("example/.swerve/{}", params.script_name), &lua, params.script_params).unwrap_or_else(|| ScriptResponse::default())
}
\ No newline at end of file
......@@ -4,8 +4,9 @@ use std::fs::File;
use std::io::Read;
use rlua::{Lua, UserData};
use scripting::ScriptResponse;
use std::collections::HashMap;
pub fn run_script<P: AsRef<Path>>(path: P, mut lua: &Lua) -> Option<ScriptResponse> {
pub fn run_script<P: AsRef<Path>>(path: P, mut lua: &Lua, params: HashMap<String, String>) -> Option<ScriptResponse> {
let mut file = File::open(&path).unwrap();
let mut buf = String::new();
......@@ -18,5 +19,13 @@ pub fn run_script<P: AsRef<Path>>(path: P, mut lua: &Lua) -> Option<ScriptRespon
.file_name()
.and_then(|name| name.to_str());
let params_table = lua.create_table().ok()?;
for (key, value) in params {
params_table.set(key, value);
}
// TODO: Inject params_table in a per-request manner
params_table.
lua.eval::<ScriptResponse>(&buf, file_name).map_err(|e| println!("{}", e)).ok()
}
\ No newline at end of file
use rlua::{UserData, UserDataMethods, Table};
use rocket::Request;
use rocket::http::Status;
use rocket::response::{Response, Responder, ResponseBuilder};
use std::default::Default;
use std::io::Cursor;
use std::default::Default;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct ScriptResponse {
pub status: u16,
pub content_type: String,
pub headers: HashMap<String, String>,
pub body: Option<String>,
}
......@@ -16,20 +19,30 @@ impl Default for ScriptResponse {
fn default() -> Self {
ScriptResponse {
status: 500,
content_type: "text/plain".into(),
body: Some("Failed to return resposne from script".into()),
headers: HashMap::new(),
body: Some("Failed to return response from script".into()),
}
}
}
impl UserData for ScriptResponse {
fn add_methods(methods: &mut UserDataMethods<Self>) {
methods.add_method_mut("set_status", |_, response: &mut ScriptResponse, status: u16| {
response.status = status;
Ok(())
})
});
methods.add_method_mut("set_header", |_, response: &mut ScriptResponse, (header, value): (String, String)| {
response.headers.insert(header, value);
Ok(())
});
methods.add_method_mut("set_body", |_, response: &mut ScriptResponse, body: String| {
response.body = Some(body);
Ok(())
});
methods.add_method_mut("unset_body", |_, response: &mut ScriptResponse, (): ()| {
response.body = None;
Ok(())
});
}
}
......@@ -37,7 +50,9 @@ impl <'r>Responder<'r> for ScriptResponse {
fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> {
let mut r = Response::build();
r.status(Status::raw(self.status));
r.raw_header("Content-Type", self.content_type);
for (name, value) in self.headers {
r.raw_header(name, value);
}
if let Some(body) = self.body {
r.sized_body(Cursor::new(body));
}
......
......@@ -4,6 +4,7 @@ use rocket::request::{FromRequest, Request};
use std::convert::{Into, AsRef, AsMut};
use scripting;
use serde::Serialize;
use std::collections::HashMap;
const LIB_JSON_ENCODE: &'static str = include_str!("../scripts/json.lua");
......@@ -28,7 +29,7 @@ impl <'a, 'req>FromRequest<'a, 'req> for LuaRuntime {
type Error = ();
fn from_request(_request: &'a Request<'req>) -> Outcome<Self, (http::Status, ()), ()> {
match create_runtime(false) {
match create_runtime(false) {
Ok(runtime) => Outcome::Success(runtime),
_ => Outcome::Failure((http::Status::raw(500), ())),
}
......@@ -49,9 +50,13 @@ pub fn create_runtime(with_debug: bool) -> LuaResult<LuaRuntime> {
{
let globals = &runtime.globals();
let response_constructor = runtime.create_function(|_, (status, content_type, body): (u16, String, String)| {
let mut headers = HashMap::new();
headers.insert(String::from("Content-Type"), content_type);
Ok(scripting::ScriptResponse {
status,
content_type,
headers,
body: Some(body),
})
})?;
......@@ -59,7 +64,7 @@ pub fn create_runtime(with_debug: bool) -> LuaResult<LuaRuntime> {
let empty_response_constructor = runtime.create_function(|_, (): ()| {
Ok(scripting::ScriptResponse {
status: 204,
content_type: "text/plain".into(),
headers: HashMap::new(),
body: None,
})
})?;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment