Skip to content

Commit

Permalink
Upgrade deno examples
Browse files Browse the repository at this point in the history
  • Loading branch information
fwqaaq committed Jun 30, 2024
1 parent ac01778 commit df41af1
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 106 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ pnpm-lock.yaml
http/grpc_example/*.pem
http/grpc_example/pb
http/grpc_example/server
cert.pem
private.pem
108 changes: 49 additions & 59 deletions http/example/authorized.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,78 +2,68 @@ const PORT = 8000
const USERNAME = 'admin'
const PASSWORD = '123456'

const conn = Deno.listen({ hostname: '0.0.0.0', port: PORT })
console.log(`Server is running on port ${PORT}`)

const server = Deno.serveHttp(await conn.accept())
const checkBasicAuth = (authHeader: string | null) => {
if (authHeader && authHeader.startsWith('Basic ')) {
const encoded = authHeader.slice(6)
const decoded = atob(encoded)
const [username, password] = decoded.split(':')
return username === USERNAME && password === PASSWORD
}
return false
}

for await (const req of server) {
const url = new URL(req.request.url)
const handler: Deno.ServeHandler = async (req) => {
const url = new URL(req.url)
const pathname = url.pathname

if (pathname === '/login') {
const authHeader = req.request.headers.get('authorization')
if (authHeader && authHeader.startsWith('Basic ')) {
const encoded = authHeader.slice(6)
const decoded = atob(encoded)
const [username, password] = decoded.split(':')
if (username === USERNAME && password === PASSWORD) {
req.respondWith(
new Response(null, {
status: 302,
headers: new Headers({
'Set-Cookie': 'authenticated=true; Path=/',
Location: '/welcome',
}),
})
)
continue
}
}
req.respondWith(
new Response('Invalid authorization', {
status: 401,
const authHeader = req.headers.get('authorization')
if (checkBasicAuth(authHeader)) {
return new Response(null, {
status: 302,
headers: new Headers({
'WWW-Authenticate':
'Basic realm="Please enter your username and password"',
'Set-Cookie': 'authenticated=true; Path=/',
Location: '/welcome',
}),
})
)
}
return new Response('Invalid authorization', {
status: 401,
headers: new Headers({
'WWW-Authenticate':
'Basic realm="Please enter your username and password"',
}),
})
} else if (pathname === '/welcome') {
console.log(req.request.headers.get('cookie'))
const isAuthorized = req.request.headers
const isAuthorized = req.headers
.get('cookie')
?.includes('authenticated=true')

if (!isAuthorized) {
req.respondWith(
new Response('Unauthorized', {
status: 401,
headers: new Headers({
'WWW-Authenticate':
'Basic realm="Please enter your username and password"',
}),
})
)
continue
return new Response(null, {
status: 302,
headers: new Headers({
Location: '/login',
}),
})
}

req.respondWith(
new Response(
new TextDecoder('utf-8').decode(await Deno.readFile('welcome.html')),
{
status: 200,
headers: new Headers({
'Content-Type': 'text/html',
}),
}
)
)
const welcomePath = new URL(import.meta.resolve('./welcome.html'))
return new Response((await Deno.open(welcomePath)).readable, {
status: 200,
headers: new Headers({
'Content-Type': 'text/html',
}),
})
} else {
req.respondWith(
new Response('Not Found', {
status: 404,
})
)
return new Response('Not Found', {
status: 404,
})
}
}

Deno.serve({
onListen({ port = PORT, hostname = 'localhost' }) {
console.log(`HTTP server listening on http://${hostname}:${port}/`)
},
handler,
})
53 changes: 15 additions & 38 deletions http/example/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,19 @@
const cert = Deno.readTextFileSync('./cert.pem')
const key = Deno.readTextFileSync('./private.pem')

const listener = Deno.listenTls({
cert,
key,
hostname: 'localhost',
port: 8080,
})

console.log('Server running on https://localhost:8080/')

for await (const conn of listener) {
handleConn(conn)
}

async function handleConn(conn: Deno.TlsConn) {
const httpConn = Deno.serveHttp(conn)

for await (const req of httpConn) {
const url = new URL(req.request.url)
if (url.pathname === '/favicon.ico') continue
const path = url.pathname === '/' ? '/welcome.html' : url.pathname
const ext = path.split('.').pop()

const file = (await Deno.open(`./http/example${path}`)).readable

let res: Response | null = null
if (ext === 'html' || ext === 'css') res = resBuilder(file, `text/${ext}`)
else if (ext === 'js') res = resBuilder(file, 'text/javascript')
else if (ext === 'png' || ext === 'jpg' || ext === 'ico')
res = resBuilder(file, `image/${ext}`)
else res = resBuilder(file, '*/*')
req.respondWith(res!)
// HTTPS server
Deno.serve(
{
cert,
key,
onListen: ({ port = 8080, hostname = 'localhost' }) => {
console.log(`Server running on https://${hostname}:${port}/`)
},
},
async (_req) => {
const welcomePath = new URL(import.meta.resolve('./welcome.html'))
return new Response((await Deno.open(welcomePath)).readable, {
headers: { 'Content-Type': 'text/html' },
})
}
}

function resBuilder(data: ReadableStream<Uint8Array>, contentType: string) {
return new Response(data, {
headers: new Headers({ 'content-type': contentType }),
})
}
)
22 changes: 13 additions & 9 deletions http/example/split_downloaded.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Server } from 'https://deno.land/[email protected]/http/server.ts'
const port = 3000

const url = new URL(import.meta.resolve('./cookie.png'))

/**
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
*/
// const handler = async (req: Request) => {
// // const body = `Your user-agent is:\n\n${req.headers.get('user-agent')}`
// const body = await Deno.readFile(url)
Expand Down Expand Up @@ -48,9 +50,11 @@ const handler = async (req: Request) => {
return new Response('Not Found', { status: 404 })
}

const server = new Server({ handler })
const listener = Deno.listen({ port })

console.log(`Listening on http://localhost:${port}/`)

await server.serve(listener)
Deno.serve(
{
onListen({ port }) {
console.log(`Listening on http://localhost:${port}/`)
},
},
handler
)

0 comments on commit df41af1

Please sign in to comment.