-
Notifications
You must be signed in to change notification settings - Fork 514
feat: implement HTTP server with request handling #468
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,45 @@ | ||
| /* eslint-disable no-console */ | ||
| 'use strict'; | ||
|
|
||
| const http = require('http'); | ||
|
|
||
| function createServer() { | ||
| /* Write your code here */ | ||
| // Return instance of http.Server class | ||
| return http.createServer((req, res) => { | ||
| const url = new URL(req.url, `http://${req.headers.host}`); | ||
| const pathname = url.pathname.slice(1).split('/'); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a good step forward, but paths with a leading or trailing slash (like |
||
|
|
||
| const searchParams = url.searchParams; | ||
|
|
||
| if (req.url.includes('..')) { | ||
| res.writeHead(404, { 'Content-Type': 'text/plain' }); | ||
| res.end('Invalid path'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (pathname.includes('//')) { | ||
| res.writeHead(404, { 'Content-Type': 'text/plain' }); | ||
| res.end('Not Found'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (pathname.length > 0 || searchParams.size > 0) { | ||
| res.writeHead(200, { 'Content-Type': 'application/json' }); | ||
|
|
||
| res.end( | ||
| JSON.stringify({ | ||
| parts: pathname, | ||
| query: Object.fromEntries(searchParams), | ||
| }), | ||
| ); | ||
| } else { | ||
| res.writeHead(404, { 'Content-Type': 'text/plain' }); | ||
| res.end('Not Found'); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| module.exports = { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This method of parsing the pathname does not correctly handle doubled slashes as required. For example, a path like
//hellowill result in['', 'hello']instead of the expected['hello']. You'll need to filter out the empty strings that result from splitting a path with multiple slashes.