Last active
October 2, 2024 16:47
-
-
Save anotherjesse/2a080568c374b75fac51908d2850d43e to your computer and use it in GitHub Desktop.
simple hash service to store data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Hono } from 'hono' | |
import { cors } from 'hono/cors' | |
import { createHash } from 'crypto' | |
const app = new Hono() | |
// Add CORS middleware | |
app.use('*', cors({ | |
origin: '*', | |
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], | |
allowHeaders: ['Content-Type', 'Authorization'], | |
exposeHeaders: ['Content-Length', 'X-Kuma-Revision'], | |
maxAge: 600, | |
credentials: true, | |
})) | |
app.get('/upload', (c) => { | |
const html = ` | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Upload Content</title> | |
</head> | |
<body> | |
<h1>Upload Content</h1> | |
<textarea id="content" rows="10" cols="50"></textarea><br> | |
<button onclick="upload()">Upload</button> | |
<p id="result"></p> | |
<script> | |
async function upload() { | |
const content = document.getElementById('content').value; | |
const response = await fetch('/', { | |
method: 'POST', | |
body: content | |
}); | |
const data = await response.json(); | |
const link = \`\${window.location.origin}/\${data.hash}\`; | |
document.getElementById('result').innerHTML = \`Your link: <a href="\${link}">\${link}</a>\`; | |
} | |
</script> | |
</body> | |
</html> | |
`; | |
return c.html(html); | |
}) | |
app.get('/:hash', async (c) => { | |
const hash = c.req.param('hash') | |
const object = await c.env.R2.get(hash) | |
if (!object) { | |
return c.text('Not Found', 404) | |
} | |
return c.body(object.body) | |
}) | |
app.post('/', async (c) => { | |
const content = await c.req.text() | |
const hash = createHash('sha256').update(content).digest('hex') | |
await c.env.R2.put(hash, content) | |
return c.json({ hash }) | |
}) | |
export default app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment