Convert to rocket rust project.

Lower memory consumption for this very simple app.
This commit is contained in:
Sage Vaillancourt 2024-06-23 10:35:53 -04:00
parent d72d8ed222
commit 1fb74fae1c
15 changed files with 1831 additions and 4233 deletions

37
.gitignore vendored
View File

@ -1,35 +1,2 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://docs.npmjs.com/cli/shrinkwrap#caveats
node_modules
# Debug log from npm
npm-debug.log
.DS_Store
.env
messages
/target
messages.log

View File

@ -0,0 +1,44 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JSCodeStyleSettings version="0">
<option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" />
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_GENERATOR_MULT" value="true" />
<option name="USE_DOUBLE_QUOTES" value="false" />
<option name="FORCE_QUOTE_STYlE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</JSCodeStyleSettings>
<TypeScriptCodeStyleSettings version="0">
<option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" />
<option name="USE_DOUBLE_QUOTES" value="false" />
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</TypeScriptCodeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
<option name="ALIGN_MULTILINE_FOR" value="false" />
<option name="SPACE_BEFORE_METHOD_PARENTHESES" value="true" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="KEEP_SIMPLE_BLOCKS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Markdown">
<option name="RIGHT_MARGIN" value="100" />
</codeStyleSettings>
<codeStyleSettings language="TypeScript">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

View File

@ -2,9 +2,11 @@
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />

1697
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

11
Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "message-me"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
chrono = "0.4.38"
rocket = "0.5.1"

39
app.js
View File

@ -1,39 +0,0 @@
const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const indexRouter = require('./routes/index')
const app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', indexRouter)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404))
})
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// render the error page
res.status(err.status || 500)
res.render('error')
})
module.exports = app

87
bin/www
View File

@ -1,87 +0,0 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require('../app')
const debug = require('debug')('message:server')
const http = require('http')
/**
* Get port from environment and store in Express.
*/
const port = normalizePort('3010')
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app)
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10)
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address()
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port
debug('Listening on ' + bind);
}

4004
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +0,0 @@
{
"name": "message",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"lint": "standard",
"lint-fix": "standard --fix"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "~2.6.1",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1"
},
"devDependencies": {
"standard": "^17.1.0"
}
}

View File

@ -1,23 +0,0 @@
const express = require('express')
const router = express.Router()
const fs = require('fs/promises')
const file = './messages'
const get = (res, thankYou) => {
res.render('index', { title: 'Message Sage 😎', thankYou })
}
/* GET home page. */
router.get('/', function (req, res, next) {
get(res, false)
})
router.post('/', (req, res) => {
const log = { message: req.body.message, timestamp: new Date() }
fs.appendFile(file, JSON.stringify(log) + '\n').catch(console.error)
get(res, true)
})
module.exports = router

70
src/main.rs Normal file
View File

@ -0,0 +1,70 @@
extern crate chrono;
#[macro_use] extern crate rocket;
use std::fs::OpenOptions;
use std::io::Write;
use chrono::Local;
use rocket::form::Form;
use rocket::fs::FileServer;
use rocket::response::content::RawHtml;
fn get(show_thank_you: bool) -> RawHtml<String> {
let message = if show_thank_you {
"<p>Message Received!</p>"
} else {
""
};
RawHtml(
format!(r###"<!DOCTYPE html>
<html>
<head>
<title>Message Sage 😎</title>
<link rel='stylesheet' href='/static/style.css' />
<meta name=viewport content="width=device-width,minimum-scale=1">
</head>
<body>
<div id="main" style="margin-left: auto; margin-right: auto; display: flex; flex-direction: column">
<h1>Message Sage 😎</h1>
<form method="POST" style="display: flex; flex-direction: column">
<label for="message" style="margin-bottom: 1em;">What did you want to say?</label>
<input id="message" name="message" type="text" style="margin-bottom: 1em;">
<button type="submit">Submit</button>
</form>
{message}
</div>
</body>
</html>
"###))
}
#[get("/")]
fn index() -> RawHtml<String> {
get(false)
}
#[derive(FromForm)]
struct MessagePost<'r> {
message: &'r str
}
#[post("/", data = "<message>")]
fn message<'r>(message: Form<MessagePost<'r>>) -> Result<RawHtml<String>, std::io::Error> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open("messages.log")
.unwrap();
let now = Local::now();
writeln!(&mut file, "{}, {}", now.format("[%Y-%m-%d, %H:%M:%S]"), message.message)?;
Ok(get(true))
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/static", FileServer::from("./static"))
.mount("/", routes![index, message])
}

View File

@ -1,3 +0,0 @@
<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>

View File

@ -1,21 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<meta name=viewport content="width=device-width,minimum-scale=1">
</head>
<body>
<div id="main" style="margin-left: auto; margin-right: auto; display: flex; flex-direction: column">
<h1><%= title %></h1>
<form method="POST" style="display: flex; flex-direction: column">
<label for="message" style="margin-bottom: 1em;">What did you want to say?</label>
<input id="message" name="message" type="text" style="margin-bottom: 1em;">
<button type="submit">Submit</button>
</form>
<% if (thankYou) { %>
<p>Message received!</p>
<% } %>
</div>
</body>
</html>