1+ const http = require ( "http" ) ;
2+ var url = require ( "url" ) ;
3+ const StringDecoder = require ( "string_decoder" ) . StringDecoder
4+
5+ const server = http . createServer ( function ( req , res ) {
6+ const {
7+ pathname : path ,
8+ query : queryStringObj
9+ } = url . parse ( req . url , true ) ;
10+ const headers = req . headers
11+ const method = req . method . toLowerCase ( ) ;
12+ const trimmedPath = path . replace ( / ^ \/ + | \/ + $ / g, '' ) ;
13+ const decoder = new StringDecoder ( 'utf-8' ) ;
14+ let buffer = '' ;
15+ req . on ( 'data' , function ( data ) {
16+ buffer += decoder . write ( data ) ;
17+ } )
18+ req . on ( 'end' , function ( ) {
19+ buffer += decoder . end ( )
20+ const choosenPath = typeof ( router [ trimmedPath ] ) !== 'undefined' ? router [ trimmedPath ] : handlers . notFound ;
21+ var data = {
22+ trimmedPath,
23+ queryStringObj,
24+ method,
25+ headers,
26+ payload : buffer
27+ }
28+
29+ choosenPath ( data , function ( statusCode , payload ) {
30+ statusCode = typeof ( statusCode ) == 'number' ? statusCode : 200 ;
31+ payload = typeof ( payload ) == 'object' ? payload : { } ;
32+ var payloadString = JSON . stringify ( payload )
33+ res . writeHead ( statusCode )
34+ res . end ( payloadString )
35+ console . log ( `request received on path: ${ trimmedPath }
36+ with method: ${ method }
37+ and query parameters: ${ JSON . stringify ( queryStringObj ) }
38+ with headers: ${ JSON . stringify ( headers ) } and payload is: ${ buffer } and response values are:
39+ ${ statusCode } and payload: ${ payloadString } ` ) ;
40+ } )
41+ } )
42+ } )
43+
44+ server . listen ( 3000 , function ( ) {
45+ console . log ( "Server is listening on port 3000 now." )
46+ } )
47+
48+ // Define handlers
49+ const handlers = { }
50+
51+ handlers . sample = function ( data , callback ) {
52+ callback ( 406 , { name : 'Sample Handler' } )
53+ }
54+
55+ // Not Found Handler
56+ handlers . notFound = function ( data , callback ) {
57+ callback ( 404 ) ;
58+ }
59+ // Defining request router
60+ const router = {
61+ 'sample' : handlers . sample
62+ }
0 commit comments